开发者

Casting Exceptions in C#

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.


You may want to try this instead:

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


System.Exception is not the object you're casting to; it's that simple. Throw an exception of the different type directly if you want to raise that type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜