2012-11-05 1 views
0

일반 대리인에서 명명 된 대리자로 변환하려고합니다. 다음 (유효하지 C#을)의 정신에있는 결과로인스턴스 메소드에 대한 위임은 null 'this'를 가질 수 없습니다. 대리자를 변환 할 때

: 나는

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

모든의를 시도

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

오류

와 함께 ArgumentException을주는 런타임에 실패

인스턴스 메소드에 대한 위임은 'this'를 null로 가질 수 없습니다.

내 코드없는 스택의 상단은 :

System.MulticastDelegate.CtorClosed에서 System.MulticastDelegate.ThrowNullThisInDelegateToInstance()

에서

(오브젝트 대상을 IntPtr methodPtr)

예외가 발생하지 않도록 대리인을 변환하는 방법은 무엇입니까?

답변

2

나는 궁극적으로 @DiegoMijelshon's solution for a question on casting delegates을 시도하여 답을 찾았습니다. 그 해결책으로 나는 ArgumentException 대신에 NullReferenceException을 얻었다. 따라서 문제는 액션 <> 내가 null (매개 변수 였음) 이었기 때문에 발견되었습니다. 따라서 다음과 같은 null 확인이 내 문제를 해결했습니다.

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

는 그때 가서 반사경 보았다 (I 빨리 했어야하는) 그것은 참으로 ThrowNullThisInDelegateToInstance가 호출되도록 매개 변수에 NULL 체크 것으로 나타났습니다.

관련 문제