Ho implementato una conversione esplicita da stringa ad oggetto chiamata Foo.Conversione esplicita generica
Quindi =>Foo f = (Foo) "dati foo"; funziona
Ho bisogno di implementare una funzione che esegue il cast di una stringa sul generico T, T in questo caso è Foo datatype.
public T Get<T>(object o){
// this always return false
if (typeof(T).IsAssignableFrom(typeof(String)))
{
// when i by pass the if above this throws invalid cast exception
return (T)(object)str;
}
return null;
}
// When I call this, it generated an error
// Invalid cast from 'System.String' to Foo
Foo myObj = Get<Foo>("another foo object");
// when I use the dynamic keyword it works but this is C# 4.0+ feature, my function is in the older framework
return (T)(dynamic)str;
Si dovrebbe usare 'TypeConverter's invece. –
Qual è la definizione di 'Foo'? Ha 'implicito' (http://msdn.microsoft.com/en-us/library/z5z9kes2%28v=vs.71%29.aspx) o' esplicito' (http://msdn.microsoft.com/ operatori di en-us/library/xhbhezf4% 28v = vs.71% 29.aspx) sovraccaricati? – CodingWithSpike
@CodingWithSpike Foo ha una conversione esplicita Foo itm = (Foo) "stringa" –