我是面向对象和编程领域的新手。有些事情我仍在努力理解。
例如,我有以下代码:
public abstract class ParentA
{
public virtual void MethodA()
{
Console.WriteLine("Doing somethin...");
}
}
public class DerivedClassA : ParentA
{
public override void MethodA()
{
Console.WriteLine("Doing something from derived...");
}
}
现在,我看到一些代码是这样初始化类的:
ParentA p = new DerivedClassA();
p.MethodA();
为什么不直接实例化您要使用的实际类并使用它的成员呢?
DerivedClassA d = new DerivedClassA();
d.MethodA();
我看到这也使用了很多接口(interface)以及这样写的地方:
public interface Animal
{
void Bark();
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("bark");
}
}
然后以这种方式使用:
Animal a = new Dog();
a.Bark();
为什么不这样做呢??:
Dog d = new Dog();
d.Bark();
什么时候重要?
感谢帮助
:)
最佳答案
你是对的;这看起来确实很奇怪,不是吗?
代码:
Animal animal = new Dog();
相当罕见;通常,如果您知道自己在制作 Dog,那么您会将变量键入 Dog。比较常见的是:
Animal animal = petStore.ObtainInexpensivePet();
你不知道会返回什么;也许是一只小猫,也许是一只鬣蜥,但你知道它至少是一只动物。是宠物店在创建狗对象,而不是您。
关于c# - 使用c#的基本对象引用和使用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4523957/