c# - 字段和属性有什么区别?

标签 c# oop properties field

在 C# 中,什么使字段与属性不同,什么时候应该使用字段而不是属性?

最佳答案

属性公开字段。字段应该(几乎总是)对类保持私有(private),并通过 get 和 set 属性访问。属性提供了一个抽象级别,允许您更改字段,同时不影响使用您的类的事物访问它们的外部方式。

public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property. When accessed it uses the underlying field,
    // but only exposes the contract, which will not be affected by the underlying field
    public string MyProperty
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }

    // This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
    // used to generate a private field for you
    public int AnotherProperty { get; set; } 
}

@Kent 指出 Properties 不需要封装字段,它们可以对其他字段进行计算,或用于其他目的。

@GSS 指出您还可以执行其他逻辑,例如在访问属性时进行验证,这是另一个有用的功能。

关于c# - 字段和属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34226301/

相关文章:

delphi - 如何制作自定义组件属性?

c# - 属性与方法

c# - 从 C# 中的 IP 获取本地网络上机器的 MAC 地址

c# - 添加一个参数,还是创建一个新方法?

javascript - 如何防止两个 Canvas 对象出现在同一个位置

java - 面向对象的执行

objective-c - @property/@synthesize 语法概要

c# - 从文件中读取值

用于嵌入式系统的 C#?

java - 我们需要 java.lang.Object 的 getClass() 方法吗?