使用公共字段的最佳做法是什么? [英] 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;
我正在创建一个名为 Result 的结构,我的目的是这样做:
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.
常量"是指任何只读的、不可变的值,而不仅仅是在 C# 中可以表示为常量"的值.
By "constant" I mean any readonly, immutable value, not just one which may be expressed as a "const" in C#.
在我看来,即使是只读的实例变量(如 Result 和 Message)也应该封装在一个属性中.
Even readonly instance variables (like Result and Message) should be encapsulated in a property in my view.
有关详细信息,请参阅这篇文章.
See this article for more details.
这篇关于使用公共字段的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!