相关疑难解决方法(0)

字段和属性之间有什么区别?

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

c# field properties

1032
推荐指数
17
解决办法
42万
查看次数

自动实现的getter和setter与公共字段

我看到很多C#类的示例代码执行此操作:

public class Point {
    public int x { get; set; }
    public int y { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

或者,在旧代码中,具有显式私有支持值并且没有新的自动实现属性:

public class Point {
    private int _x;
    private int _y;

    public int x {
        get { return _x; }
        set { _x = value; }
    }

    public int y {
        get { return _y; }
        set { _y = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么.在执行上述操作与仅将这些成员设为公共字段之间是否有任何功能差异,如下所示?

public class Point {
    public int x;
    public int y;
}
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,当您需要对基础数据进行一些翻译时,我理解了getter和setter的价值.但是,如果你只是传递价值观,那似乎是不必要的冗长.

c# oop field properties

71
推荐指数
6
解决办法
3万
查看次数

标签 统计

c# ×2

field ×2

properties ×2

oop ×1