2012-11-05 81 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要調用的參數空校驗。