有人知道关于在抽象类或父类中公共(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/