我可以使用 get 和 set 代码创建自动属性(无私有成员)吗?

发布于 2024-07-15 12:50:06 字数 485 浏览 5 评论 0原文

在 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 技术交流群。

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

发布评论

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

评论(4

离不开的别离 2024-07-22 12:50:06

不,无法使用现有版本的 C# 或 C# 4.0 中的属性来执行此操作。

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

手心的温暖 2024-07-22 12:50:06

正如其他人所说,没有内置的方法可以做到这一点。

您可以使用 PostSharp 实现类似的效果。 但我不确定这是否值得付出努力。

[AfterSet(DoSomething)]
public int Foo {
    get;
    set;
}

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;
}
千纸鹤 2024-07-22 12:50:06

通过自动属性,编译器会为您生成一个支持字段。 自定义 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.

迷荒 2024-07-22 12:50:06

简短的回答? 不,长答案? 抱歉,还是没有。 :) 我感受到你的痛苦,但事实就是这样。

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

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