Can I create an automatic property (no private member) with get and set code?

元气小坏坏 提交于 2019-12-02 12:11:35

问题


In c#, I can do this:

public int Foo { get; set; }

Which is nice. But as soon as I want to do anything in the getter or setter, I have to change it to this:

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

Is it possible to avoid this? I would love to be able to do something like this:

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

How close can I get to the above?


回答1:


No, there's no way to do this with properties in an existing version of C#, or C# 4.0.




回答2:


As others have said, there is no builtin way to do this.

You could achieve something kind of similar with PostSharp. But I'm not sure its worth the effort.

[AfterSet(DoSomething)]
public int Foo {
    get;
    set;
}



回答3:


With automatic properties, the compiler generates a backing field for you. A custom getter/setter requires that you manually create a backing field to work with. The ability to specify a custom getter/setter on an automatic property would essentially make it act just like a method, since there's nothing to get or set.




回答4:


The short answer? No. The long answer? Sorry, still no. :) I feel your pain man, but that's the way it is.



来源:https://stackoverflow.com/questions/664883/can-i-create-an-automatic-property-no-private-member-with-get-and-set-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!