在C#铸造异常 [英] Casting Exceptions in C#

查看:143
本文介绍了在C#铸造异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我得到一个试图做到这一点时, InvalidCastException的



 掷(ArgumentNullException)(新的异常(errormessage的,NULL)); 

这是下面的函数的简化版本。

 公共静态无效的要求< T>(布尔断言,字符串消息,异常的InnerException)其中T:(!断言)异常
{
如果
{
掷(T)(新的异常(消息的InnerException));
}
}



完整的错误信息是:




System.InvalidCastException:无法投类型'System.Exception的'对象键入'System.ArgumentNullException'

解决方案

我有你实例化一个基类,并试图将它转换为一个派生类的印象。我不认为你能做到这一点,因为异常比ArgumentNullException更通用。你可以做它周围的其他方法虽然。


Why do I get an InvalidCastException when trying to do this?

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

This is a simplified version of the following function.

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

The complete error message is:

System.InvalidCastException : Unable to cast object of type 'System.Exception' to type 'System.ArgumentNullException'.

解决方案

I have the impression that you are instantiating a base class and trying to cast it as a derived class. I don't think you are able to do this, as Exception is more "generic" than ArgumentNullException. You could do it the other way around though.

这篇关于在C#铸造异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆