这不是常见的情况。我试图通过反射调用异常。我有类似的东西: testMethod的类型为MethodBuilder
testMethod.GetILGenerator().ThrowException(typeof(CustomException));
我的CustomException没有默认构造函数,因此上面的语句错误地给出了ArgumentException。如果有默认构造函数,则可以正常工作。
那么有没有办法,这可以使用没有默认的构造函数?已经尝试了2个小时了。 :(
感谢任何帮助。
谢谢!
答案 0 :(得分:5)
ThrowException
方法基本归结为以下
Emit(OpCodes.NewObj, ...);
Emit(OpCodes.Throw);
这里的关键是用创建自定义异常实例所需的一组IL指令替换第一个Emit
调用。然后添加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);
答案 1 :(得分: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);