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

public int Foo { get; set; }


很好但是,只要我想在getter或setter中执行任何操作,就必须将其更改为:

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


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

public int Foo {
    get;
    set {
       DoSomething();
    }
}


我能接近上述距离吗?

最佳答案

不,没有办法使用C#或C#4.0的现有版本中的属性来执行此操作。

关于c# - 我可以使用get和set代码创建自动属性(无私有(private)成员)吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/664883/

10-17 02:32