Voglio convertire un oggetto in un tipo che verrà assegnato in fase di esecuzione.Convertire un tipo al volo in C# .NET
Ad esempio, si supponga di avere una funzione che assegna un valore di stringa (da TextBox or Dropdownlist
) a Object.Property
.
Come convertire il valore nel tipo corretto? Ad esempio, potrebbe essere un numero intero, una stringa o enum.
Public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type t= obj.GetType().GetProperty(propName).PropertyType;
//Now Setting the property to the value .
//But it raise an error,because sometimes type is int and value is "2"
//or type is enum (e.a: Gender.Male) and value is "Male"
//Suppose that always the cast is valid("2" can be converted to int 2)
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
puoi dare un esempio dove questo sarebbe usato? Se non conosci il tipo concreto, perché dovresti lanciarlo? Hai pensato di andare dinamici? – Carsten
Sai qual è il tipo quando passi l'argomento nel metodo 'Foo'? –
@JamesJohnson Penso che puoi sempre scoprire se hai bisogno :-) – username