2010-11-19 200 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);