c# - 抽象类中的属性可见性

标签 c# properties

有人知道关于在抽象类或父类中公共(public)属性背后定义属性可见性(私有(private)或 protected )的方式的 C# 最佳实践吗?

在其他世界中,什么是默认最佳实践(以及为什么):

public abstract class MyClass
{
    private string myAttribute;

    public string MyAttribute
    {
        get { return myAttribute; }
        set { myAttribute = value; }
    }
}

public abstract class MyClass
{
    protected string myAttribute;

    public string MyAttribute
    {
        get { return myAttribute; }
        set { myAttribute = value; }
    }
}

我认为子类应该有办法直接处理这个 protected 属性,但如果 getter 或 setter 包含更多代码,这可能不是一个好的做法......

你怎么看?

谢谢。

最佳答案

非常量字段应该始终是私有(private)的。如果由于某种原因不能使用自动属性而需要使用某个字段,请确保它是私有(private)的。子类应通过公共(public)或 protected 属性访问它。

关于c# - 抽象类中的属性可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2148132/

相关文章:

swift - 使用 Swift 中对象的自定义 setter 方法设置依赖属性变量

python - 我应该使用描述符类还是属性工厂?

c# - 通过具有不同属性类型的反射设置对象的属性

c# - 动态文本框绑定(bind)

maven - org.codehaus.mojo :properties-maven-plugin:1. 0-alpha-2 错误

ios - 从另一个类访问一个类变量的值 - Objective-C

c# - 无法使用 C# 将时间转换为 ISO 8601

c# - 是否可以将 BackgroundWorker 类与 .net 核心一起使用?

c# - 为什么 ThreadPool.SetMinThreads 没有改变最小值?

c# - 无法转换属性的范围键值