简体   繁体   English

是否可以在子类上定义成员而无需在抽象父类上定义它? C#

[英]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? 这只是一个例子......在这种情况下,属性MyName没有在父类中定义,但它在子类中......是否可能?

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. 你的int x属性会导致问题,因为会有两个不同的x属性在运行。

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 Child类应该通过添加新成员或修改现有成员的行为来“扩展”父类

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. 您提供的代码是合法的C#程序,这意味着您的意图是为子类创建不同的int x。 This is often not the case and Microsoft C# compiler will give you a warning about it. 通常情况并非如此,Microsoft C#编译器会向您发出警告。

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. 您唯一不能做的就是访问MyName属性,如果您要通过父级。 In that case you would just have acces to those common to MyParent. 在这种情况下,您只需访问MyParent常用的那些。

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

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