[英]Difference between the reference types of derived and base classes
Guys i want your help please.伙计们,我需要你的帮助。
We Have This Code:我们有这个代码:
class Program
{
static void Main(string[] args)
{
Animal pig = new Pig();
Pig pig2 = new Pig();
List<Animal> Animals = new List<Animal>();
Animals.Add(pig);
Animals.Add(pig2);
foreach(Animal a in Animals)
{
Animal.AnimalSound();
}
}
}
class Animal
{
public virtual void AnimalSound()
{
Console.WriteLine("AnimalSound");
}
}
class Pig : Animal
{
public override void AnimalSound()
{
Console.WriteLine("wee wee!");
}
}
My Question is as i instantiate variables pig and pig2 what's the difference Animal pig = new Pig();我的问题是当我实例化变量 pig 和 pig2 时有什么区别 Animal pig = new Pig(); and Pig pig2 = new Pig();和 Pig pig2 = new Pig();
Why not declare them both as ReferenceType Pig since Pig is as always Animal????为什么不将它们都声明为 ReferenceType Pig,因为 Pig 一如既往地是 Animal????
The difference is, name is not accessible when you do this Animal pig = new Pig();
不同的是,当你执行这个Animal pig = new Pig();
时, name是不可访问的Animal pig = new Pig();
, but name is accessible in this case Pig pig2 = new Pig();
,但在这种情况下可以访问名称Pig pig2 = new Pig();
. . You always inherit from base class because you want to use some ready made behavior from parent, and want to add some child specific behavior in child class.您总是从基类继承,因为您想使用来自父类的一些现成的行为,并希望在子类中添加一些特定于子类的行为。 Pig is always an animal, but all animals are not Pig.猪永远是动物,但所有的动物都不是猪。
class Pig : Animal
{
public string name;
public override void AnimalSound()
{
Console.WriteLine("wee wee!");
}
}
So you have base class Animal
and derived class Pig
.所以你有基类Animal
和派生类Pig
。 So our question can be concluded to what's difference between base and derived classes:所以我们的问题可以归结为基类和派生类之间的区别:
Base class is a class from which other classes are derived.基类是派生其他类的类。
Derived class is a class that is created on the basis of an existing class.派生类是在现有类的基础上创建的类。 Some features of derived class:派生类的一些特点:
Private
properties are not accessible due to the accessibility level, however you can use reflection to read their values.由于可访问性级别, Private
属性不可访问,但是您可以使用反射来读取它们的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.