简体   繁体   English

通过引用具有继承类类型的对象来创建基类类型变量

[英]creating a base class type variable with the reference to an object with the type of an inheriting class

class Program
{
    static void Main(string[] args)
    {
        BaseC instance = new DerivedC();
        // I don't see Y here.
        Console.ReadLine();
    }
}

public class BaseC
{
    public int x;
}
public class DerivedC : BaseC
{
    public int y;
}

I'm talking about the first line in the Main function. 我说的是Main函数的第一行。 When I create it like this: DerivedC instance = new DerivedC(); 当我这样创建它时:DerivedC instance = new DerivedC(); everything's clear for me, and I see both variables, but why don't I see Y when creating an object that way above? 一切对我来说都很清楚,而且我看到了两个变量,但是为什么以上述方式创建对象时却看不到Y? How does the type of the 'instance' variable (either BaseC or DerivedC) affect the result? 'instance'变量的类型(BaseC或DerivedC)如何影响结果?

That's the way polymorphism works in C#: in a variable of a base class type, you are allowed to store a reference to an instance of any subclass - but if you choose to do that, you can only "see" the base class members through the variable. 这就是多态在C#中的工作方式:在基类类型的变量中,您可以存储对任何子类实例的引用-但是,如果选择这样做,则只能通过以下方式“查看”基类成员:变量。 The reason for this is safety: it is guaranteed that no matter what the variable refers to, it will have an x . 这样做的原因是安全性:保证无论变量引用什么,它都会有一个x However, there might exist other subclasses that do not have a y . 但是,可能存在其他没有y子类。

You might argue that it's obvious that the variable refers to an DerivedC , but that's just because this is a simple example. 您可能会争辩说,很明显该变量引用了DerivedC ,但这仅仅是因为这是一个简单的示例。 Imagine some code where there is a function that takes a BaseC as a parameter. 想象一下一些代码,其中有一个将BaseC作为参数的函数。 The function might be called in one place with a DerivedC , and in another place with a DifferentDerivedC that doesn't have a y . 可以在一个地方用DerivedC调用该函数,而在另一个地方用不带yDifferentDerivedC调用。 Then, the function would fail in the second call if it were allowed to access y . 然后,如果允许该函数访问y ,则该函数将在第二次调用中失败。

Because the type of instance is BaseC, it will not expose Property y. 因为实例的类型是BaseC,所以它不会公开Property y。 To access Property y, you will need to do like below: 要访问Property y,您需要执行以下操作:

((DerivedC)instance).y

y is an extended property which is accessible only from the Child Class. y是一个扩展属性,只能从子类访问。 That is the concept of Inheritence. 那就是继承的概念。 The Child inherits the properties on child, not the other way round. Child继承child的属性,而不是相反。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM