属性与其中一个(二传手或getter)与body



这个问题只是出于好奇。我有以下属性

public static int MyProperty {get;set;}

编译成功,但是当我这样做时

public static int MyProperty {
    get
    {
        return 5;
    }
    set;
}

public static int MyProperty {
    get;
    set
    {
        value = 10;
    }
}

然后我收到错误

"ClassName.MyProperty.set"必须声明一个主体,因为它不是 标记为抽象、外部或部分

'ClassName.MyProperty.get' 必须声明一个主体,因为它不是 标记为抽象、外部或部分

分别。

我的问题是为什么不为getter和setter提供身体,而是为任何一个提供身体,并给出错误?

因为当你使用它时: { get; set; }被称为自动属性,它只是拥有支持字段的快捷方式。与此相同:

{ 
  get { return _field; }
  set { _field = value; }
}

但这不能只与两个部分中的一个一起使用。

任何属性都应该为其 getter 和 setter 定义逻辑(如果有的话(。
空的getter或空的setter没有任何意义。

但是,当您定义如下属性时:

public static int MyProperty { get; set; }

您告诉 C# 自动生成支持字段并用于简单的等效实现:

// This is actually what it means:
private static int _myProperty; // name for simplicity
public static int MyProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}   

或者如果进一步扩展它:

// This is actually what it means:
private static int _myProperty; // name for simplicity
public static int get_MyProperty()
{
    return _myProperty; 
}
public static void set_MyProperty(int value)
{
    _myProperty = value; 
}

当您使用一个自动获取器和编码资源库定义属性时,它实际上没有多大意义。您希望属性的get在此代码中执行什么操作?

public static int MyProperty {
    get;
    set
    {
        value = 10;
    }
}

最新更新