为什么我在尝试执行此操作时会收到 InvalidCastException
?
throw (ArgumentNullException)(new Exception("errormessage", null));
这是以下函数的简化版本。
public static void Require<T>(bool assertion, string message, Exception innerException) where T: Exception
{
if (!assertion)
{
throw (T)(new Exception(message, innerException));
}
}
完整的错误信息是:
System.InvalidCastException : Unable to cast object of type 'System.Exception' to type 'System.ArgumentNullException'.
最佳答案
我的印象是您正在实例化一个基类并试图将其转换为派生类。我认为您无法做到这一点,因为 Exception 比 ArgumentNullException 更“通用”。不过你也可以反过来做。
关于c# - 在 C# 中转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3384392/