通用类型例外

Dot*_*ent 2 c# generics .net-3.5

最近我遇到了在泛型方法中使用给定消息创建异常的问题.例如,以下代码按预期工作:

public static void Throw<T>() where T : Exception, new()
{
    throw new T();
}

...

public static void Main()
{
    Throw<ArgumentOutOfRangeException>(); // Throws desired exception but with a generic message.
}
Run Code Online (Sandbox Code Playgroud)

但是,我希望能够写

public static void Throw<T>(string message) where T : Exception, new()
{
    T newException = new T();

    newException.Message = message; // Not allowed. 'Message' is read-only.

    throw newException;
}

...

public static void Main()
{
    Throw<ArgumentOutOfRangeException>("You must specify a non-negative integer."); // Throws desired exception.
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在不使用反射来改变Message属性的值或用所需参数动态激活类型实例的情况下实现这一目的?

Fel*_* K. 8

您可以使用它Activator.CreateInstance(typeof(T), "MyException description")来启用自定义消息.

没有使用反射或使用激活器就无法创建实例.

看到

http://msdn.microsoft.com/de-de/library/wcxyzt4d(v=vs.80).aspx