简体   繁体   中英

Is it possible to define member on a child class without defining it on the abstract parent class? C#

Just to clarify, is it really mandatory that all the members of a child class are declared on the abstract class above it?

Would be possible something like this:

public abstract class MyParent
{
    public int x { get; set; }
}
public class MyChild : MyParent
{
    public int x { get; set; }
    public string MyName { get; private set; }
}

It's just an example... In such case, the property MyName is not defined in the parent class, but it is in the child class... Is it possible?

Thanks in advance!

Yes, you can declare additional properties and methods in the child class.

However, if you are using a variable that is declared to be the ancestor type, you will only be able to access the members defined in the ancestor type through that variable. The only way to get to the child class's special stuff is to typecast down to the child type.

As an aside: the child class should not duplicate the declarations made in the ancestor. Your int x property here will cause problems because there will be two different x properties running around.

A concrete (non-abstract) child class is required to override any virtual methods or properties declared in the abstract ancestor. Virtual and override both require specific keywords in the declaration.

Yes it is possible to create new members in a child class that are not in the parent class. That's the whole point of having child classes. Child class is supposed to "extend" a parent class by adding new members or modifying the behavior of existing members

However, You need not recreate parent class members in the child classes. Child classes get all the members from the parent class automatically.

The code you have given is a legal C# program and it means that your intention is to create a different int x for the child class. This is often not the case and Microsoft C# compiler will give you a warning about it.

yes of course it's very normal for you to do this. The only thing you can't do though is access the MyName property if you are going through the parent. In that case you would just have acces to those common to MyParent.

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