抽象类中的属性可见性 [英] Property visibility in abstract class
问题描述
有人知道在抽象类或父类中在公共属性后面定义属性可见性(私有或受保护)的方式的 C# 最佳实践吗.
Does someone knows C# best practice about the way to define attribute visibility (private or protected) behind public property in abstract class or parent class.
在其他世界中,默认情况下的最佳实践是什么(以及为什么):
In other worlds what is the best practice by default (and why) between:
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; }
}
}
我认为子类应该有办法直接处理这个受保护的属性,但如果 getter 或 setter 包含更多代码,这可能不是一个好习惯...
I think children class should have the way to handle directly this protected attribute but it may not be a good practice if getter or setter contains more code...
你怎么看?
谢谢.
推荐答案
非常量字段应该始终是私有的.如果由于某种原因无法使用自动属性而需要使用某个字段,请确保它是私有的.子类应该通过公共或受保护的属性访问它.
Non-const fields should be really always private. If you need to use a field because you cannot use auto-properties for some reason, make sure it's private. Children classes should access it via public or protected properties.
这篇关于抽象类中的属性可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!