mi chiedo se qualcuno potrebbe spiegare il motivo per cui in questo codicePerché un parametro dinamico in un metodo generico genera un'eccezione di riferimento null quando si utilizza un oggetto?
public class SomeClass
{
public T GenericMethod<T>(dynamic value)
{
return (T)value;
}
}
il 'valore di ritorno;' dichiarazione genera un'eccezione riferimento null quando viene chiamato con:
new SomeClass().GenericMethod<object>(new object()); // throws System.NullReferenceException
Esso funziona come previsto quando viene chiamato con:
new SomeClass().GenericMethod<string>("SomeString"); // returns SomeString
new SomeClass().GenericMethod<object>("SomeString"); // returns SomeString
Nota: I seguenti compila e funziona bene
public class SomeOtherClass
{
public T GenericMethod<T>(object value)
{
return (T)value;
}
}
The stacktrace:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.CSharp.RuntimeBinder.ExpressionTreeCallRewriter.GenerateLambda(EXPRCALL pExpr)
at Microsoft.CSharp.RuntimeBinder.Semantics.ExprVisitorBase.Visit(EXPR pExpr)
at Microsoft.CSharp.RuntimeBinder.ExpressionTreeCallRewriter.Rewrite(TypeManager typeManager, EXPR pExpr, IEnumerable`1 listOfParameters)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.BindCore(DynamicMetaObjectBinder payload, IEnumerable`1 parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind(DynamicMetaObjectBinder payload, IEnumerable`1 parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding)
at Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind(DynamicMetaObjectBinder action, RuntimeBinder binder, IEnumerable`1 args, IEnumerable`1 arginfos, DynamicMetaObject onBindingError)
at Microsoft.CSharp.RuntimeBinder.CSharpConvertBinder.FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
at System.Dynamic.DynamicMetaObject.BindConvert(ConvertBinder binder)
at System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection`1 parameters, LabelTarget returnLabel)
at System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
Nizza trovare! Speriamo che qualche esperto di compilatori abbia una spiegazione. –
Sospetto che abbia qualcosa a che fare con il cast dinamico su 'T' (anche se il tipo effettivo è lo stesso). Se fai 'restituire il valore come T' funziona pure. –
La parola chiave dynamic indica al compilatore di non applicare regole aggiuntive sul codice, motivo per cui penso che sia consentito compilare. Per quanto riguarda il tipo di ritorno effettivo, sembra che l'argomento di input del valore contenga un valore e sembra come se fosse possibile eseguire il cast del valore ('value as T', ad esempio) –