【发布时间】:2011-06-24 18:51:52
【问题描述】:
在 c# 中使用公共字段而不是属性是否有好处? 如果没有好的案例可以使用它们,为什么它们可以在该语言中使用?
【问题讨论】:
标签: c#
在 c# 中使用公共字段而不是属性是否有好处? 如果没有好的案例可以使用它们,为什么它们可以在该语言中使用?
【问题讨论】:
标签: c#
Public Fields 打破了封装的原则,将类对象的内部状态暴露给外界。这并不意味着您会或不应该这样做,但通过属性公开您的内部状态是一种更好的做法,这样您就可以提供验证或其他保护技术,以防止恶意用户以潜在危险的方式随机更改您的状态。当然,您也可以在类方法中编写逻辑来验证正确的状态以及适合您的状态。
【讨论】:
常量是我能想到的一个重要例子。如果您有一个基本上只是以常量(字符串、整数等)形式提供数据的类,那么为每个类都设置一个属性是没有意义的。
【讨论】:
一般来说,公共只读字段很有用。它们在结构中也很有用,尤其是用于互操作目的,例如:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
/// <summary>
/// The x-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Left;
/// <summary>
/// The y-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Top;
/// <summary>
/// The x-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Right;
/// <summary>
/// The y-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Bottom;
}
【讨论】:
使用public static readonly string 比使用public static string{get;} 稍微高效一些,因为前者消除了方法调用开销。另一方面,我认为这会被编译器优化掉。
【讨论】:
我还注意到,当您在 ASP.NET 页面上使用变量时,您可能需要在后面的代码中将变量声明为 public。不确定是否有其他方法。
【讨论】:
.NET 属性纯粹是语法糖,仅此而已。无论如何,CLR 在引擎盖下使用烘焙字段创建相同的 set/get 方法。拥有一个公共属性而不是公开公共字段,这稍微有点 OOP,它使您能够控制条目的验证,例如,在 setter 上。
【讨论】:
如果您不需要任何内部处理,请使用公共字段。
例如;
public string Description;
将与
完全相同private string _description;
public string Description
{
get { return _description; }
set { _description= value; }
}
但是,后者将允许您做其他事情;
public string Description
{
get {
//Do something here
}
set {
//Do something here
}
}
【讨论】:
public string Description;。