Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将异常强制转换为ArgumentException?_C#_Exception_Casting - Fatal编程技术网

C# 无法将异常强制转换为ArgumentException?

C# 无法将异常强制转换为ArgumentException?,c#,exception,casting,C#,Exception,Casting,抛出: System.InvalidCastException:无法将类型为“System.Exception”的对象强制转换为类型为“System.ArgumentException” 为什么我不能对ArgumentException(我认为定义更少)强制转换一个异常(我认为定义更多)?这就像尝试做: ArgumentException argumentException = (ArgumentException)new Exception(); 它将读取或写入哪个文件 只有当实际对象是某个

抛出:

System.InvalidCastException:无法将类型为“System.Exception”的对象强制转换为类型为“System.ArgumentException”


为什么我不能对ArgumentException(我认为定义更少)强制转换一个异常(我认为定义更多)?

这就像尝试做:

ArgumentException argumentException = (ArgumentException)new Exception();
它将读取或写入哪个文件

只有当实际对象是某个类型或在其层次结构中具有该类型时,才能强制转换对该类型的引用。因此,这将起作用:

FileStream stream = (FileStream) new object();
这也会起作用:

Exception exception = new ArgumentException();
ArgumentException argumentException = (ArgumentException) exception;
但您的示例不会,因为just
System.Exception
的实例不是
System.ArgumentException
的实例


请注意,这与异常无关,实际上-相同的逻辑适用于所有引用类型。(对于值类型还有拳击/拆箱要考虑。哦,还有潜在的用户定义的转换,例如从<代码> xBase<代码> > <代码>字符串 >但是我们将暂时离开这些代码。)

因为你正在创建一个<代码>异常< /代码>对象,而不是一个<代码>参数< /代码>异常。您正在尝试将对象强制转换为您正在实例化的类型的后代。您可以这样做:

Exception exception = new ArgumentOutOfRangeException();
// An ArgumentOutOfRangeException *is* an ArgumentException
ArgumentException argumentException = (ArgumentException) exception;
但你不能这样做:

Exception ex = new ArgumentException();
为什么我不能对ArgumentException(我认为是更多定义)抛出一个例外(我认为是更少定义)

因为附加信息(“更多定义”)必须来自某个地方。只有当基地实际上是伪装的衍生基地时,才能从基地向衍生基地施放

我喜欢
(FileStream)新对象()
示例。很好地说明了这一点。
ArgumentException ex = (ArgumentException)new Exception();