动态抛出“System.ArgumentException”时“发现不明确的匹配”

Moo*_*ice 3 .net c# reflection

考虑这个函数:

static void Throw<T>(string message) where T : Exception
{
    throw (T)Activator.CreateInstance(typeof(T), message, (Exception)null);
}
Run Code Online (Sandbox Code Playgroud)

T正如问题标题所示,给定类型System.ArgumentException,我收到“找到不明确匹配”的运行时错误。查看 的文档ArgumentException,以下是公共构造函数:

ArgumentException()
ArgumentException(string)
ArgumentException(SerializationInfo, StreamingContext)
ArgumentException(string, Exception)
ArgumentException(string, string)
ArgumentException(string, string, Exception)
Run Code Online (Sandbox Code Playgroud)

鉴于我将 2 个参数传递给CreateInstance,并强制null为 null Exception,我很难理解为什么它与上面列表中的第四个构造函数不匹配?

Dmi*_*nko 5

那可行:

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});
}
Run Code Online (Sandbox Code Playgroud)

典型Exception4 个或更多构造函数,因此我们宁愿指出我们要执行哪一个。通常,我们必须检查是否有合适的构造函数:

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});
  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,在您的情况下,您可以将其与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);
}
Run Code Online (Sandbox Code Playgroud)