This question already has answers here:
Why is casting a dynamic of type object to object throwing a null reference exception?
(4个答案)
4年前关闭。
我想知道是否有人可以解释为什么在此代码中
“返回值”;调用时,语句抛出空引用异常:
可以通过以下方式按预期工作:
注意:
以下编译并运行正常
堆栈跟踪:
(4个答案)
4年前关闭。
我想知道是否有人可以解释为什么在此代码中
public class SomeClass
{
public T GenericMethod<T>(dynamic value)
{
return (T)value;
}
}
“返回值”;调用时,语句抛出空引用异常:
new SomeClass().GenericMethod<object>(new object()); // throws System.NullReferenceException
可以通过以下方式按预期工作:
new SomeClass().GenericMethod<string>("SomeString"); // returns SomeString
new SomeClass().GenericMethod<object>("SomeString"); // returns SomeString
注意:
以下编译并运行正常
public class SomeOtherClass
{
public T GenericMethod<T>(object value)
{
return (T)value;
}
}
堆栈跟踪:
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)
最佳答案
看来it's a bug于2012年首次报告,但显然仍未修复(截至2016年5月24日)
09-06 05:03