使用的getter和setter一个支持变量变量、getter、setter

由网友(还没长大就老了)分享简介:也许这是一个愚蠢的问题,但是,我是合理的新的C#(更从Java背景),并已得到了困惑我所看到的关于财产的getter和setter方法​​不同的例子的。在某些情况下,code是这样的:私人字符串_something;公共字符串东西{{返回_something; }集合{_something =价值; }}然而,在其他的...

也许这是一个愚蠢的问题,但是,我是合理的新的C#(更从Java背景),并已得到了困惑我所看到的关于财产的getter和setter方法​​不同的例子的。

在某些情况下,code是这样的:

 私人字符串_something;
    公共字符串东西
    {
        {返回_something; }
        集合{_something =价值; }
    }
 

然而,在其他的例子,他们不使用此后盾memeber,所以它更像是这样的:

 公共字符串东西{获得;组; }
 
谨慎使用getter setter

我实在不明白使用这些变量的支持(_something)的利益,当然,除非你有关于变量的设置一些复杂的逻辑。

我写用后一种方法我的程序,但想检查我没有错过任何东西。

有人可以简单地解释为什么人们选择了做前?它是更多的好习惯?

非常感谢!

解决方案   

我实在不明白使用这些变量的支持(_something)的利益,当然,除非你有关于变量的设置一些复杂的逻辑。

还有,如果你不使用它是没有什么优势。在第二种方法中,仍然有来头的变量,但你让编译器做其添加的工作。作为.NET 3.5和更高版本,目前的做法是完全合法的。

当然,只要你需要引入额外的逻辑,那么管理后备存储自己变得至关重要。

Perhaps this is a silly question, however, I am resonable new to C# (more from a Java background) and have got confused between different examples I have seen regarding getters and setters of a property.

In some situations the code looks like this:

    private string _something;
    public string Something
    {
        get { return _something; }
        set { _something = value; }
    }

However, in other examples they do not use this backing memeber and so it is more like this:

    public string Something { get; set; }

I do not really see the benefit of using these backing variables (_something) unless of course you have some complex logic regarding the setting of the variables.

I am writing my program using the latter approach, but wanted to check I have not missed anything.

Can someone please explain simply why people chose to do the former? Is it more 'good practice'?

Thanks a lot!

解决方案

I do not really see the benefit of using these backing variables (_something) unless of course you have some complex logic regarding the setting of the variables.

There is no advantage if you're not using it. With the second approach, there is still a backing variable, but you're letting the compiler do the work of adding it. As of .NET 3.5 and later, your current approach is perfectly valid.

Of course, as soon as you need to introduce extra logic, then managing the backing store yourself becomes critical.

阅读全文

相关推荐

最新文章