考虑这个功能:
static void Throw<T>(string message) where T : Exception
{
throw (T)Activator.CreateInstance(typeof(T), message, (Exception)null);
}
给定
T
的类型 System.ArgumentException
,如问题标题所述,我收到“找到不明确匹配”的运行时错误。查看ArgumentException
的文档,以下是公共构造函数:
ArgumentException()
ArgumentException(string)
ArgumentException(SerializationInfo, StreamingContext)
ArgumentException(string, Exception)
ArgumentException(string, string)
ArgumentException(string, string, Exception)
鉴于我将 2 个参数传递给
CreateInstance
,并强制 null
为空 Exception
,我很难理解为什么它与上面列表中的第四个构造函数不匹配?
这会起作用:
static void Throw<T>(String message)
where T: Exception { // <- It's a good style to restrict T here
throw (T) typeof(T).GetConstructor(new Type[] {typeof(String)}).Invoke(new Object[] {message});
}
典型的
Exception
有 4 或更多构造函数,所以我们宁愿指出我们想要执行哪一个。通常,我们必须检查是否有合适的构造函数:
static void Throw<T>(String message)
where T: Exception { // <- It's a good style to restrict T here
// The best constructor we can find
ConstructorInfo ci = typeof(T).GetConstructor(new Type[] {typeof(String)});
if (!Object.ReferenceEquals(null, ci))
throw (T) ci.Invoke(new Object[] {message});
// The second best constructor
ci = typeof(T).GetConstructor(new Type[] {typeof(String), typeof(Exception)});
if (!Object.ReferenceEquals(null, ci))
throw (T) ci.Invoke(new Object[] {message, null});
...
}
但是,在您的情况下,您可以将其与
Activator
:
static void Throw<T>(String message)
where T: Exception { // <- It's a good style to restrict T here
throw (T) Activator.CreateInstance(typeof(T), message);
}
这可能有用
static void Throw<T>(string message)
{
Exception ex = null;
throw (Exception)Activator.CreateInstance(typeof(T), message, ex);
}
我不知道
Exception
在这个列表中的哪个位置,但我猜它和string
一样具体,否则就不会有问题。 当传递空值时,方法重载解析系统如何决定调用哪个方法?
此调用不会将异常类型传递给激活器,从而将其与至少两个签名相匹配。
解决方案。当inner为空时,仅提供消息,或(message, paramName, inside)