在 C# 中,我可以让自动属性在属性的帮助下执行一些额外的工作吗?

发布于 2024-09-03 18:33:25 字数 592 浏览 3 评论 0原文

这个问题相关但与此不同:如何你给 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月隐月明月朦胧 2024-09-10 18:33:26

您可以使用 AOP 来完成此操作,例如 Postsharp,但在这种情况下为什么不只使用后备存储呢?

另外,为了完整起见,您可能应该这样做:

someName = (value ?? string.Empty).Trim();

也处理 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:

someName = (value ?? string.Empty).Trim();

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 2024-09-10 18:33:26

不,没有办法做到这一点。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文