2010-11-19 3 views
4

이것은 일반적인 시나리오는 아닙니다. 리플렉션을 통해 예외를 호출하려고합니다. testMethod 유형의 MethodBuilder입니다리플렉션을 통한 ThrowException

testMethod.GetILGenerator().ThrowException(typeof(CustomException)); 

내 CustomException는 기본 생성자, 그래서 경우 ArgumentException을주는 위의 진술 오류 아웃이되지 않습니다 내가 좋아하는 뭔가가있다. 기본 생성자가 있으면 정상적으로 작동합니다.

이렇게 기본 생성자없이 작동하는 방법이 있습니까? 지금 2 시간 동안 노력하고있어. :(

어떤 도움에 감사드립니다

감사

답변

2

가 참조 documentation :.!

// This example uses the ThrowException method, which uses the default 
// constructor of the specified exception type to create the exception. If you 
// want to specify your own message, you must use a different constructor; 
// replace the ThrowException method call with code like that shown below, 
// which creates the exception and throws it. 
// 
// Load the message, which is the argument for the constructor, onto the 
// execution stack. Execute Newobj, with the OverflowException constructor 
// that takes a string. This pops the message off the stack, and pushes the 
// new exception onto the stack. The Throw instruction pops the exception off 
// the stack and throws it. 
//adderIL.Emit(OpCodes.Ldstr, "DoAdd does not accept values over 100."); 
//adderIL.Emit(OpCodes.Newobj, _ 
//    overflowType.GetConstructor(new Type[] { typeof(String) })); 
//adderIL.Emit(OpCodes.Throw); 
5

ThrowException 방법은 기본적으로 다음과 같은

Emit(OpCodes.NewObj, ...); 
Emit(OpCodes.Throw); 

키 아래로 비등 여기에 첫 번째로 교체하는 것입니다 Emit 사용자 정의 예외 인스턴스를 작성하는 데 필요한 IL 명령 세트를 호출합니다. 그리고 예를 들어, Emit(OpCodes.Throw)

를 추가

class MyException : Exception { 
    public MyException(int p1) {} 
} 

var ctor = typeof(MyException).GetConstructor(new Type[] {typeof(int)}); 
var gen = builder.GetILGenerator(); 
gen.Emit(OpCodes.Ldc_I4, 42); 
gen.Emit(OpCodes.NewObj, ctor); 
gen.Emit(OpCodes.Throw); 
관련 문제