考虑这个函数:
static void Throw<T>(string message) where T : Exception
{
throw (T)Activator.CreateInstance(typeof(T), message, (Exception)null);
}
鉴于 System.ArgumentException 的类型 T,如问题标题所述,我收到运行时错误“找到不明确的匹配项”。查看ArgumentException 的文档,以下是公共(public)构造函数:
ArgumentException()
ArgumentException(string)
ArgumentException(SerializationInfo, StreamingContext)
ArgumentException(string, Exception)
ArgumentException(string, string)
ArgumentException(string, string, Exception)
假设我将 2 个参数传递给 CreateInstance,并强制 null 为 null Exception,我很难理解为什么它与上面列表中的第 4 个构造函数不匹配?
请您参考如下方法:
这会起作用:
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);
}
