学习自动实现的属性 [英] Learning about Auto-Implemented Properties

查看:139
本文介绍了学习自动实现的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用自动实现性的判定的简单的类:

 公共类Foo
{
    公共富(){}

    公共字符串BarName {获得;组;}
}
 

我明明用我的整个类变量BarName现在需要添加逻辑,当属性值设置(它必须是全部大写,去图)。这是否意味着我现在需要创造BarName,例如,一个私有变量_BarName,并改变贯穿我的类_BarName目前BarName变量?

 公共类Foo
{
    公共富(){}

    私人字符串_BarName =;
    公共字符串BarName
    {
        {返回_BarName;}
        集合{_BarName = Value.ToString()ToUpper的();}
    }
}
 

我想确保我了解使用自动实现的属性的影响,以及它会在道路上带来当/如果我需要改变某些事情了。我假设的重构,如上图所示,是不是改变,因为该属性是基本保持不变;它只是花了一点工作类中继续保持这种方式,并添加所需的逻辑。

另外一个例子,这可能是更有意义的是,我需要打电话的时候,一个设置或吸气剂中使用的一些方法;更多的则更改值。

这似乎是一个公平的折衷线和code线设置属性。

解决方案
  

这是否意味着我需要现在   对于BarName创建一个私有变量

  

和改变当前BarName   变量用于整个班上

不要在类中使用你创建新的私有变量改变的code中的其余部分。 BarName 的,作为一个属性,是为了隐藏私有变量(除其他事项外),以避免你考虑到你的code,其余的巨大变化的目的。

  

我假设的重构,如   如上图所示,是不是一个重大更改   因为属性是基本   保持相同;它只是花了   一些工作来保持这种方式和   添加所需的逻辑。

正确的。

I have the simple class using auto-implemented properies:

Public Class foo
{
    public foo() { }  

    public string BarName {get; set;}
}

I obviously use the variable BarName throughout my class and now need to add logic when the property value is set (it must be all upper case, go figure). Does this mean that I need to now create a private variable for BarName , e.g. _BarName, and change the current BarName variable used throughout my class to _BarName?

Public Class foo
{
    public foo() {}  

    private string _BarName = "";
    public string BarName 
    { 
        get {return _BarName;}
        set {_BarName = Value.ToString().ToUpper();}
    }
}

I am trying to make sure I understand the implications of using auto-implemented properties, and what it will entail down the road when/if I need to change something. I am assuming that the refactoring, as shown above, is not a breaking change because the property is basically staying the same; it just took a little work inside the class to keep it that way and add the needed logic.

Another example, which may be more meaningful is that I need to call some method when a setter or getter is used; more then changing the value.

This seems a fair trade off the the lines and lines of code to setup properties.

解决方案

Does this mean that I need to now create a private variable for BarName

Yes

and change the current BarName variable used throughout my class

Do not change the rest of the code in your class to use the new private variable you create. BarName, as a property, is intended to hide the private variable (among other things), for the purpose of avoiding the sweeping changes you contemplate to the rest of your code.

I am assuming that the refactoring, as shown above, is not a breaking change because the property is basically staying the same; it just took a little work to keep it that way and add the needed logic.

Correct.

这篇关于学习自动实现的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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