简体   繁体   中英

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. When I create it like this: 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? How does the type of the 'instance' variable (either BaseC or DerivedC) affect the result?

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. The reason for this is safety: it is guaranteed that no matter what the variable refers to, it will have an x . However, there might exist other subclasses that do not have a 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. Imagine some code where there is a function that takes a BaseC as a parameter. The function might be called in one place with a DerivedC , and in another place with a DifferentDerivedC that doesn't have a y . Then, the function would fail in the second call if it were allowed to access y .

Because the type of instance is BaseC, it will not expose Property y. To access Property y, you will need to do like below:

((DerivedC)instance).y

y is an extended property which is accessible only from the Child Class. That is the concept of Inheritence. The Child inherits the properties on child, not the other way round.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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