加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 了解自动实现的属性

发布时间:2020-12-15 19:41:03 所属栏目:百科 来源:网络整理
导读:我有使用自动实现的属性的简单类: Public Class foo{ public foo() { } public string BarName {get; set;}} 我显然在我的类中使用变量BarName,现在需要在设置属性值时添加逻辑(它必须全部为大写,如图).这是否意味着我现在需要为BarName创建一个私有变量,例
我有使用自动实现的属性的简单类:

Public Class foo
{
    public foo() { }  

    public string BarName {get; set;}
}

我显然在我的类中使用变量BarName,现在需要在设置属性值时添加逻辑(它必须全部为大写,如图).这是否意味着我现在需要为BarName创建一个私有变量,例如_BarName,并将我班级中使用的当前BarName变量更改为_BarName?

Public Class foo
{
    public foo() {}  

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

我正在努力确保我理解使用自动实现的属性的含义,以及当我/如果我需要更改某些内容时它会带来什么.我假设重构,如上所示,不是breaking的变化,因为该属性基本上保持不变;它只是在课堂上做了一些工作,以保持这种方式并添加所需的逻辑.

另一个可能更有意义的例子是我需要在使用setter或getter时调用某个方法;更多然后改变价值.

这似乎是设置属性的代码行和行的公平交易.

解决方法

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

and change the current BarName
variable used throughout my class

不要更改类中的其余代码以使用您创建的新私有变量. BarName作为一个属性,旨在隐藏私有变量(以及其他内容),以避免您考虑对代码的其余部分进行全面更改.

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.

正确.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读