在C#中转换exception

尝试执行此操作时为什么会出现InvalidCastException

 throw (ArgumentNullException)(new Exception("errormessage", null)); 

这是以下function的简化版本。

 public static void Require(bool assertion, string message, Exception innerException) where T: Exception { if (!assertion) { throw (T)(new Exception(message, innerException)); } } 

完整的错误消息是:

System.InvalidCastException:无法将类型为’System.Exception’的对象强制转换为’System.ArgumentNullException’。

我的印象是您正在实例化一个基类并尝试将其转换为派生类。 我不认为你能做到这一点,因为Exception比ArgumentNullException更“通用”。 你可以反过来做到这一点。

您可能想尝试这样做:

 public static void Require(bool assertion, string message, Exception innerException) where T: Exception { if (!assertion) { throw (Exception) System.Activator.CreateInstance( typeof(T), message, innerException); } } 

System.Exception不是您要转换的对象; 就这么简单。 如果要提升该类型,请直接抛出不同类型的exception。