我想测试下面的代码:
private bool TestException(Exception ex)
{
if ((Marshal.GetHRForException(ex) & 0xFFFF) == 0x4005)
{
return true;
}
return false;
}
我想以某种方式设置 Exception
对象以返回正确的 HResult,但我在 Exception
类中看不到允许这样做的字段。
我该怎么做?
最佳答案
我找到了三种方法:
使用
System.Runtime.InteropServices.ExternalException
类,将错误代码作为参数传入:var ex = new ExternalException("-", 0x4005);
感谢@HansPassant感谢他解释这一点的评论。
使用继承传递模拟异常以访问 protected 字段:
private class MockException : Exception { public MockException() { HResult = 0x4005; } } var ex = new MockException();
使用 .NET 反射设置底层字段:
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; FieldInfo hresultFieldInfo = typeof(Exception).GetField("_HResult", flags); var ex = new Exception(); hresultFieldInfo.SetValue(ex, 0x4005);
将这些异常中的任何一个传递给问题中的方法,将导致该方法返回 true
。我怀疑第一种方法最有用。
关于c# - 我怎样才能抛出带有特定 HResult 的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11158379/