你不是在施法 - 你正在使用as操作员.如果你真的投了,我怀疑你会得到一个例外:
var student = (Students) o;
Run Code Online (Sandbox Code Playgroud)
我怀疑你实际上有多种类型被调用Students,如果你真的投射而不是使用as你会看到所涉及的实际类型.
例如:
using System;
namespace Bad
{
class Students {}
class Test
{
static void Main()
{
object o = new Good.Students();
Students cast = (Students) o;
}
}
}
namespace Good
{
class Students {}
}
Run Code Online (Sandbox Code Playgroud)
这导致:
Unhandled Exception: System.InvalidCastException:
Unable to cast object of type 'Good.Students' to type 'Bad.Students'.
at Bad.Test.Main()
Run Code Online (Sandbox Code Playgroud)
请注意如何在异常中获取完全限定的类型名称.
一般来说,使用它是一个坏主意,as除非你真的希望对象可能不是正确的类型,并且通常你之后会检查它.有关详细信息,请参阅我关于该主题的博客文章.