什么是使用公共领域的最佳实践? [英] What is the best practice for using public fields?
问题描述
当我写一个类,我总是通过一个公共属性像这样公开私有字段:
When I write a class I always expose private fields through a public property like this:
private int _MyField;
public int MyField
{ get{return _MyField; }
当那是正确的,只是公开公共领域是这样的:
When is it ok to just expose a public field like this:
public int MyField;
我创建了一个名为结果结构,我的意思是这样做:
I am creating a structure called Result and my intention is do this:
public Result(bool result, string message)
{
Result = result;
Message = message;
}
public readonly int Result;
public readonly int Message;
什么是最好的做法是什么?是以往任何时候都好做呢?
What is the best practice? Is it ever ok to do this?
推荐答案
我只揭露公共领域时,他们(静态)常数 - 即使如此,我通常会使用属性
I only ever expose public fields when they're (static) constants - and even then I'd usually use a property.
通过恒定我的意思是任何只读,不可变的价值,而不只是其中一个可能是pssed在C#中的常量EX $ P $。
By "constant" I mean any readonly, immutable value, not just one which may be expressed as a "const" in C#.
即使是只读的实例的变量(如结果和消息)应该被封装在我看来,一个属性。
Even readonly instance variables (like Result and Message) should be encapsulated in a property in my view.
请参阅这篇文章了解更多详情。
这篇关于什么是使用公共领域的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!