我可以使用 get 和 set 代码创建自动属性(无私有成员)吗?
在 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();
}
}
我能离上面的目标有多近?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,无法使用现有版本的 C# 或 C# 4.0 中的属性来执行此操作。
No, there's no way to do this with properties in an existing version of C#, or C# 4.0.
正如其他人所说,没有内置的方法可以做到这一点。
您可以使用 PostSharp 实现类似的效果。 但我不确定这是否值得付出努力。
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.
通过自动属性,编译器会为您生成一个支持字段。 自定义 getter/setter 要求您手动创建一个要使用的支持字段。 在自动属性上指定自定义 getter/setter 的能力本质上会使其像方法一样工作,因为无需获取或设置任何内容。
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.
简短的回答? 不,长答案? 抱歉,还是没有。 :) 我感受到你的痛苦,但事实就是这样。
The short answer? No. The long answer? Sorry, still no. :) I feel your pain man, but that's the way it is.