我试图基于传递给方法的异常类型参数抛出异常.
这是我到目前为止,但我不想指定每种例外:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想做一些事情,new T(message)因为我有一个基本类型SystemException我会认为这是某种可能的.
我不认为你可以单独使用gerics来做到这一点.你需要使用反射.就像是:
throw (T)Activator.CreateInstance(typeof(T),message);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
871 次 |
| 最近记录: |