考虑以下功能:

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)


鉴于我要向CreateInstance传递2个参数,并强制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);
}

关于c# - 动态抛出“System.ArgumentException”时出现“歧义匹配”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21455135/

10-10 15:10