我可以创建一个自动属性(没有私有成员)使用get和set代码? [英] Can I create an automatic property (no private member) with get and set code?

查看:123
本文介绍了我可以创建一个自动属性(没有私有成员)使用get和set代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我可以这样做:

In c#, I can do this:

public int Foo { get; set; }



这是很好的。但只要我想在getter或setter做任何事情,我必须把它改成这样:

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?

推荐答案

没有,有没有办法在C#或C#4.0的现有版本的属性做到这一点。

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

这篇关于我可以创建一个自动属性(没有私有成员)使用get和set代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆