根据类型参数实例化新对象

时间:2011-11-17 08:57:33

标签: c# type-parameter

我试图根据传递给方法的异常类型参数抛出异常。

这是我到目前为止所做的,但我不想指出各种例外:

public void ThrowException<T>(string message = "") where T : SystemException, new()
    {
        if (ConditionMet)
        {
            if(typeof(T) is NullReferenceException)
                throw new NullReferenceException(message);

            if (typeof(T) is FileNotFoundException)
                throw new FileNotFoundException(message);

            throw new SystemException(message);
        }
    }

理想情况下,我希望做一些像new T(message)这样的事情,因为我的基本类型为SystemException我会认为这是某种可能的。

3 个答案:

答案 0 :(得分:6)

我认为你不能单独使用gerics来做到这一点。你需要使用反射。类似的东西:

throw (T)Activator.CreateInstance(typeof(T),message);

答案 1 :(得分:1)

正如其他人所说,这只能通过反思来完成。但是你可以删除type参数并将实例化的异常传递给函数:

public void ThrowException(Exception e)
{
    if (ConditionMet)
    {
        if(e is NullReferenceException || e is FileNotFoundException)
        {
            throw e;
        }

        throw new SystemException(e.Message);
    }
}

用法:

// throws a NullReferenceException
ThrowException(new NullReferenceException("message"));
// throws a SystemException
ThrowException(new NotSupportedException("message"));

答案 2 :(得分:0)

您可以使用

Activator.CreateInstance(typeof(T),message);

更多http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx