c# - 在 C# 中转换异常

标签 c# exception casting

为什么我在尝试执行此操作时会收到 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/

相关文章:

java - 找不到 Hibernate 4 ConnectionProvider 类

c# - C# 中的内联 'try' 语句可能吗?

C++ 指针转换帮助,void* 到 bool 值

swift - Any 在 Swift 中的转换失败?协议(protocol)

c# - 对于给定的优先级,Dispatcher.Invoke() 和 Dispatcher.BeginInvoke() 是否相等?

django - 最好的 Django syncdb 崩溃调试技术是什么?

c# - 如何在Windows Phone 8中使用对象导航?

c++ - (string)char 类型转换

c# - WPF:将 DataGridTemplateColumn 中的元素绑定(bind)到另一个 DataGridTemplateColumn 中的元素

c# - 如何保存 ref 变量供以后使用?