2012-11-05 84 views
0

我想从一个通用委托转换为一个命名委托。对实例方法的委托不能具有null'this'。当转换委托人

有了结果如下(无效C#)的精神是:

Action<CustomClass> act = ???; 
CustomDelegate d = act; 

我已经试过

CustomDelegate d = act.Invoke; 
CustomDelegate d = new CustomDelegate(act); 
CustomDelegate d = new CustomDelegate(x => act(x)); 
CustomDelegate d = new CustomDelegate(act.Invoke); 

所有这一切都不能在运行时错误

给人一种 ArgumentException

对实例方法的委托不能具有null'this'。

堆栈这不是我的代码的顶部是:

在System.MulticastDelegate.ThrowNullThisInDelegateToInstance()

在System.MulticastDelegate.CtorClosed(对象目标,IntPtr的methodPtr)

如何将一个委托转换为我没有得到异常?

回答

2

我最终通过尝试@DiegoMijelshon's solution for a question on casting delegates找到答案。有了这个解决方案,我得到了NullReferenceException而不是ArgumentException。因此我发现这个问题是因为行动<>我是空的(这是一个参数)。因此,像下面这样的空检查解决了我的问题。

CustomDelegate d = adt == null ? null : act.Invoke; 
// Though, I actually went with @DiegoMijelshon solution to avoid extra indirection. 

然后我去与反射镜看(我应该早点完成),发现它确实是针对导致ThrowNullThisInDelegateToInstance要调用的参数空校验。