使用的getter和setter一个支持变量 [英] Using a backing variable for getters and setters

查看:134
本文介绍了使用的getter和setter一个支持变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

 公共字符串东西{获得;组; }
 

我实在不明白使用这些变量的支持(_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.

这篇关于使用的getter和setter一个支持变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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