Ho un string
e un Type
e voglio convertire il valore string
convertito in quello Type
.Converti da stringa a qualsiasi tipo base
public static object StringToType(string value, Type propertyType)
{
return Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
}
Ciò restituisce un object
che posso utilizzare in una chiamata valore di insieme di proprietà:
public static void SetBasicPropertyValueFromString(object target,
string propName,
string value)
{
PropertyInfo prop = target.GetType().GetProperty(propName);
object converted = StringToType(value, prop.PropertyType);
prop.SetValue(target, converted, null);
}
Questo funziona per la maggior parte dei tipi di base, ad eccezione nullables.
[TestMethod]
public void IntTest()
{ //working
Assert.AreEqual(1, ValueHelper.StringToType("1", typeof (int)));
Assert.AreEqual(123, ValueHelper.StringToType("123", typeof (int)));
}
[TestMethod]
public void NullableIntTest()
{ //not working
Assert.AreEqual(1, ValueHelper.StringToType("1", typeof (int?)));
Assert.AreEqual(123, ValueHelper.StringToType("123", typeof (int?)));
Assert.AreEqual(null, ValueHelper.StringToType(null, typeof (int?)));
}
NullableIntTest
fallisce in prima linea con:
System.InvalidCastException: cast non valida dal 'System.String' a 'System.Nullable`1 [[System.Int32, mscorlib, Version = 4.0 .0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]] '.
Ho difficoltà a rilevare se il tipo è annullabile e modifica il comportamento del metodo StringToType
.
Comportamento Sono dopo:
Se stringa è nulla o vuota, restituire NULL, altrimenti convertire secondo tipo non nullable.
Risultato
Come risposta di Kirill, solo con un ChangeType
chiamata.
public static object StringToType(string value, Type propertyType)
{
var underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{
//an underlying nullable type, so the type is nullable
//apply logic for null or empty test
if (String.IsNullOrEmpty(value)) return null;
}
return Convert.ChangeType(value,
underlyingType ?? propertyType,
CultureInfo.InvariantCulture);
}
È possibile rendere il vostro metodo generico: 'StringToType (valore stringa) oggetto statico pubblico dove T: struct' ... –
@KarelFrajtak Na, a causa del modo in cui è chiamato, vedi il secondo frammento di codice. 'prop.PropertyType' è di riflessione, quindi non è noto fino al runtime. – weston
Il tuo controllo 'if' non è corretto. I tuoi casi speciali non dovrebbero essere per * qualsiasi * tipo generico, dovrebbe essere * solo * per un 'Nullable' perché sono in scatola in modo diverso. –
Servy