简体   繁体   English

扩展了C#中用于类的简单getter,setter方法

[英]Extends simple getter, setter Methods for Classes in C#

I have a abstract class 'Building': 我有一个抽象类“建筑”:

public abstract class Building {
abstract public int ID {get;}
abstract public string name {get;}
}

the class (for example) Headquarter : Building has the Variables for these getter and setter methods. 该类(例如)Headquarter:Building具有这些getter和setter方法的变量。 The Problem is I have to write in every Subclass 问题是我必须在每个子类中编写

private int _ID = 1;
public int ID {
    get {return _ID;}
}

Is there a way to create for example one getter setter method like ahead, in the abstract class and save the code, so that I only have to set the variables? 有没有一种方法可以在抽象类中创建例如前面的getter setter方法并保存代码,这样我只需要设置变量? Thanks for helping. 感谢您的帮助。

Instead of making the properties abstract, you could make the setter protected, and/or allow them to be set in the constructor: 您可以使setter受保护,和/或允许在构造函数中进行设置,而不是使属性抽象化:

public abstract class Building 
{
    // Optional constructor
    protected Building(int id, string name)
    {
         this.ID = id;
         this.Name = name;
    }

    public int ID { get; protected set; }
    public string Name { get; protected set; }
}

This moves the implementation into the base class, but still only allows the subclasses to set those values. 这会将实现移到基类中,但仍仅允许子类设置这些值。

You can try adding a protected setter in base class and set the value in ctor of derived classes: 您可以尝试在基类中添加protected setter,并在派生类的ctor中设置值:

public class Building
{
     public int Id{get;protected set;}

and in derived class: 并在派生类中:

public class Headquarter: Building
{
    public Headquarter()
    {
        Id = 1;
    }
}

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

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