有人可以解釋這兩部分代碼之間的主要區別,以及爲什麼或何時應該使用對基類的引用,如對我來說,這是一回事。爲什麼要使用對基類的引用,我無法理解差異
internal class MyBaseClass
{
public string Field = "Hello";
public void Print()
{
Console.WriteLine("This is the base class.");
}
}
internal class MyDerivedClass : MyBaseClass
{
public string FieldDerived = "Coucou";
public new void Print()
{
Console.WriteLine("This is the derived class.");
}
public new void Print2()
{
Console.WriteLine("This is the derived class.");
}
}
internal class Program
{
private static void Main()
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass) derived;
// ↑
// Cast to base clas
}
}
這是代碼,這爲我做的完全一樣的事情:
internal class MyBaseClass
{
public string Field = "Hello";
public void Print()
{
Console.WriteLine("This is the base class.");
}
}
internal class MyDerivedClass : MyBaseClass
{
public string FieldDerived = "Coucou";
public new void Print()
{
Console.WriteLine("This is the derived class.");
}
public new void Print2()
{
Console.WriteLine("This is the derived class.");
}
}
internal class Program
{
private static void Main()
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = new MyBaseClass();
// ↑
// Use the base class
}
}
什麼是什麼? – Jodrell 2013-04-29 13:43:38
我可以訪問完全相同的方法/領域,與派生和mybc,我真的不明白什麼是參考點。 – Meds 2013-04-29 13:45:31
看起來像下面的調用 - MyBaseClass mybc = new MyBaseClass(); vs.(MyBaseClass)派生;' – wjhguitarman 2013-04-29 13:45:59