C# 以下属性C之间有什么区别

C# 以下属性C之间有什么区别,c#,properties,C#,Properties,我正在使用这两个属性 一, 二, 这两个属性之间有什么区别。没有。两者都是相同的,只是您可以从第一个代码段执行此操作,而第二个代码段不能执行此操作 int x = 0; public int X { get { return x; } set { if (value < 0) // A guard condition or some custom condition here value =

我正在使用这两个属性

一,

二,


这两个属性之间有什么区别。

没有。两者都是相同的,只是您可以从第一个代码段执行此操作,而第二个代码段不能执行此操作

int x = 0;

public int X
{
    get
    {
        return x;
    }
    set
    {
        if (value < 0) // A guard condition or some custom condition here
            value = 0;

        x = value;
    }
}
如以下示例所示声明属性时 编译器创建一个私有的匿名支持字段,该字段只能是 通过属性的get和set访问器访问


唯一的区别是,在您的示例中,您仍然可以直接获取/设置支持字段,而不是使用属性。对于自动实现的属性,您无法做到这一点。

请检查:-那么简单变量和第二个代码段之间有什么区别。您在第一个代码段中所做的事情是由编译器在第二个代码段中自动完成的。但是,如果您想在设置和提取值时控制局部变量和属性的值,可以使用我在回答中所写的代码段。
 public string ID
 {
     get;
     set;
 }
int x = 0;

public int X
{
    get
    {
        return x;
    }
    set
    {
        if (value < 0) // A guard condition or some custom condition here
            value = 0;

        x = value;
    }
}
private double seconds;

public double Hours
{
    get { return seconds / 3600; }
    set { seconds = value * 3600; }
}