2012-02-24 11 views
15

Ho il codice qui sotto e avevo bisogno di convertire una stringa in un tipo che è anche specificato da Stringa:Come convertire una stringa in un tipo Nullable Che è determinato in fase di esecuzione?

Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); 

      object d = Convert.ChangeType("2012-02-23 10:00:00", t); 

ottengo il messaggio di errore di seguito:

Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. 

Come sarebbe che essere gentilmente possibile?

So che un brutto modo sarebbe quello di verificare se il tipo è annullabile con se:

Type possiblyNullableType = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); 

    var underlyingType = Nullable.GetUnderlyingType(possiblyNullableType); 

    Object result; 

    // if it's null, it means it wasn't nullable 
    if (underlyingType != null) 
    { 
     result = Convert.ChangeType("2012-02-23 10:00:00", underlyingType); 
    } 

Ci sarebbe un modo migliore?

Grazie,

risposta

29

Ci sono due problemi .

In primo luogo, Convert.ChangeType semplicemente non supporta i tipi nullable.

In secondo luogo, anche se lo fosse, eseguendo il boxing del risultato (assegnandolo a un object), lo convertiresti già in un DateTime.

Si potrebbe casi speciali tipi nullable:

string s = "2012-02-23 10:00:00"; 
Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); 
object d; 

if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) 
{ 
    if (String.IsNullOrEmpty(s)) 
     d = null; 
    else 
     d = Convert.ChangeType(s, t.GetGenericArguments()[0]); 
} 
else 
{ 
    d = Convert.ChangeType(s, t); 
} 
+0

Perché dovresti controllare t.IsGenericType? la parte t.GetGenericTypeDefinition() == typeof (Nullable <>) lo coprirebbe; non lo sarebbe? –

+2

@William 'GetGenericTypeDefinition()' genera un'eccezione se il tipo non è generico. – hvd

1

Qualcosa di simile? A meno che tu non abbia davvero bisogno di farlo dinamicamente.

if (string.IsNullOrEmpty(input)) 
{ 
    return new DateTime?(); 
} 
else 
{ 
    return new DateTime?(DateTime.Parse(input)); 
} 

Forse si potrebbe verificare per vedere se il tipo è uno dei tipi 'nullable' e poi magari si poteva trovare qualcosa di utile qui:

Convert string to nullable type (int, double, etc...)

+0

posso' t specificare DateTime, è determinato in fase di runtime. –

+0

'return new DateTime?();' Deve essere sostituito da 'return null;'. – ken2k

+0

Forse se potessi fornire ulteriori informazioni su ciò che stai cercando di fare in contrasto con quello che stai facendo, potremmo consigliarlo? – Paddy

9

ho scritto il metodo di supporto generico di sotto del quale opera in maggior parte degli scenari (non testato con i tipi generici):

static void Main(string[] args) 
{ 
    Object result = 
     ConvertValue(
      "System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", 
      "2012-02-23 10:00:00"); 
} 

public static Object ConvertValue(string typeInString, string value) 
{ 
    Type originalType = Type.GetType(typeInString); 

    var underlyingType = Nullable.GetUnderlyingType(originalType); 

    // if underlyingType has null value, it means the original type wasn't nullable 
    object instance = Convert.ChangeType(value, underlyingType ?? originalType); 

    return instance; 
} 
+0

Grazie. Questa è la soluzione più elegante e funzionante. –

2
public static T GetValue<T>(string Literal, T DefaultValue) 
    { 
     if (Literal == null || Literal == "" || Literal == string.Empty) return DefaultValue; 
     IConvertible obj = Literal; 
     Type t = typeof(T); 
     Type u = Nullable.GetUnderlyingType(t); 

     if (u != null) 
     { 
      return (obj == null) ? DefaultValue : (T)Convert.ChangeType(obj, u); 
     } 
     else 
     { 
      return (T)Convert.ChangeType(obj, t); 
     } 
    } 
Problemi correlati