lan*_*nce 0 c# casting exception
ArgumentException argumentException = (ArgumentException)new Exception();
Run Code Online (Sandbox Code Playgroud)
抛出:
System.InvalidCastException:无法将类型为"System.Exception"的对象强制转换为"System.ArgumentException".
为什么我不能将一个Exception(更少的定义,我会想到)转换为ArgumentException(更多的定义,我想)?
这就像试图做:
FileStream stream = (FileStream) new object();
Run Code Online (Sandbox Code Playgroud)
它会读取或写入什么文件?
如果实际对象是该类型或在其层次结构中具有该类型,则只能转换对类型的引用.所以这将有效:
Exception exception = new ArgumentException();
ArgumentException argumentException = (ArgumentException) exception;
Run Code Online (Sandbox Code Playgroud)
这也会奏效:
Exception exception = new ArgumentOutOfRangeException();
// An ArgumentOutOfRangeException *is* an ArgumentException
ArgumentException argumentException = (ArgumentException) exception;
Run Code Online (Sandbox Code Playgroud)
但是你的例子不会因为just 的实例System.Exception 不是实例System.ArgumentException.
请注意,这与异常无关,实际上 - 所有引用类型都应用相同的逻辑.(对于值类型有也是装箱/拆箱考虑哦,还有,也是潜在的用户定义的转换,例如从XElement到string-但我们会离开那些出它太的时刻.)
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |