开发者

Inject extra things into default get'ters and set'ters for properties

Normally you can do something like this for properties:

public String s {get; set; }

to make a property with default getters and setters.

Additionally, you can implement both of them yourself.

But can I only 'implemement' one of them, say the setter, to do extra things ?

Say something like

public String s {
  get;
  set { 
    // some extra cod开发者_开发问答e here to happen on any setting of this property
  }

}

It appears I can't do this (doesn't compile) and have to introduce a helper private variable, and fill out appropriately the get/set code. Any ideas?

Thanks!


No, you can't - automatically implemented properties are "all or nothing"; they can only ever implement completely trivial properties. You'll need to introduce a field yourself.

(Personally I don't mind that too much, but I'd really like to be able to write read-only automatic properties which can only be set from the constructor.)


Unfortunately, compiler won't allow what you're trying to do. You can setup an auto property like so...

public String s { get; private set;}

Then have a special set method...

public void SetS(string s)
{
     ...logic
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜