我可以使用get和set代码创建自动属性(没有私有成员)吗?

Blo*_*ard 1 c# properties automatic-properties

在c#中,我可以这样做:

public int Foo { get; set; }
Run Code Online (Sandbox Code Playgroud)

这很好.但是只要我想在getter或setter中做任何事情,我就必须将其更改为:

private int foo;
public int Foo {
    get { return foo; }
    set {
        foo = value;
        DoSomething();  // all that other code, just to add this line!
    }
}
Run Code Online (Sandbox Code Playgroud)

有可能避免这种情况吗?我希望能够做到这样的事情:

public int Foo {
    get;
    set {           
       DoSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

我有多接近上述?

Dus*_*ell 6

不,没有办法在现有版本的C#或C#4.0中使用属性.