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

前端 未结 4 538
后悔当初
后悔当初 2021-01-24 02:14

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 chang

相关标签:
4条回答
  • 2021-01-24 02:28

    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;
    }
    
    0 讨论(0)
  • 2021-01-24 02:32

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

    0 讨论(0)
  • 2021-01-24 02:37

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

    0 讨论(0)
  • 2021-01-24 02:48

    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.

    0 讨论(0)
提交回复
热议问题