在 C# 中,我可以让自动属性在属性的帮助下执行一些额外的工作吗?
这个问题相关但与此不同:如何你给 C# 自动属性一个默认值吗?
我喜欢自动属性,但有时我必须做这样的事情:
private string someName;
public string SomeName
{
get
{
return someName;
}
set
{
someName = value.Trim();
}
}
如果我必须多次做同样的事情,我开始希望我没有这样做需要输入这么多行/字符的代码。我希望能够拦截该值并像这样更改它:
public string Somename
{
get;
[Trim]
set;
}
有没有办法做这样的事情?会不会很傻?有更好的办法吗?还有其他一般性评论吗?我承认,我给出的例子有点假设,我现在无法找到让我想到这一点的确切代码。
谢谢。
This question is related but not the same as this: How do you give a C# Auto-Property a default value?
I love auto-properties, but sometimes I have to do something like this:
private string someName;
public string SomeName
{
get
{
return someName;
}
set
{
someName = value.Trim();
}
}
If I have to do the same thing many times, I start wishing that I did not need to type so many lines/characters of code. I want to be able to intercept the value and change it sort of like so:
public string Somename
{
get;
[Trim]
set;
}
Is there a way to do something like this? Would it be stupid? Is there a better way? Any other general comments? I admit, the example I gave is a bit hypothetical and I cannot locate the exact code now which made me think of this.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 AOP 来完成此操作,例如 Postsharp,但在这种情况下为什么不只使用后备存储呢?
另外,为了完整起见,您可能应该这样做:
也处理
null
。请注意,如果您心中有一个涉及更多工作的特定案例,您可能应该询问该案例,而不是问题中的琐碎案例
You can do it using AOP, like with Postsharp, but why aren't you just using a backing store in this case?
Also, for completeness, you should probably do this:
to handle
null
as well.Note that if you have a specific case in mind where there is more work involved, you should probably ask about that case, and not the trivial one you have in your question
不,没有办法做到这一点。 C# 自动属性只是最简单的属性的语法糖,仅此而已。
No there is not a way to do this. C# auto properties are meant to be syntactic sugar for only the most trivial of properties and nothing more.