C# 如何将基类强制转换为派生类
为什么不能将基类强制转换为派生类?还有,为什么编译器没有捕捉到这一点C# 如何将基类强制转换为派生类,c#,C#,为什么不能将基类强制转换为派生类?还有,为什么编译器没有捕捉到这一点 namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Parent p = new Parent(); Child c = (Child)p; } } class Parent
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Parent p = new Parent();
Child c = (Child)p;
}
}
class Parent
{
public string Data { get; set; }
}
class Child : Parent
{
public string OtherDate { get; set; }
}
}
p
是Parent
的一个实例,因此您不能告诉运行时将其解释为一个实例
编译器无法捕获它,因为这样的代码
Parent p = new Child();
Child c = (Child)p;
而且编译器不进行捕获它所需的静态代码分析。不检查的原因有:
- 这很费时
- 它只能捕获一些错误实例
c.OtherDate
做什么?