简体   繁体   中英

force property implementation on derived classes

I have Person.cs which will be implemented by, for example, the Player class. Person has an ExperienceLevelType property.

I want to force all classes that derived from Person to implement their own version of the ExperienceLevelType property.

public abstract Person
{
    public enum ExperienceLevel { Kid, Teenager}
    public virtual ExperienceLevel Experience {get; set;}
}

public abstract Player:Person
{
    public override ExperienceLevel Experience
    {

    }
}

That's what abstract is for:

public abstract class Person
{
    public enum ExperienceLevel { Kid, Teenager}
    public abstract ExperienceLevel Experience { get; set; }
}

If you want to force derived classes to implement the property themselves while at the same time providing some reusable scaffolding to help them, expose the scaffolding as protected members inside Person .

您可以使Person成为一个接口(并且没有任何IPerson ),或者您可以使Person实现一个具有您属性的自定义接口IPerson

您需要做的就是将方法声明为抽象方法,它会强制子类实现它。

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