您是否使用数据成员或公共属性从类本身? [英] Do you use Data Members or Public Properties from within the Class itself?

查看:168
本文介绍了您是否使用数据成员或公共属性从类本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个简单的类设置是这样的:

If I have a simple class setup like this:

class MyClass
{
    private string _myName = string.Empty;

    public string MyName
    {
        get
        {
            return _myName;
        }
    }

    public void DoSomething()
    {
        // Get the name...
        string name = string.Empty;

        name = _myName;

        // OR

        name = MyName;

        // ...and do something with it...
    }
}

我应该使用哪种,公共财产,或者数据成员?

Which should I use, the public property, or the data member?

显然,在这个例子中它没有区别,因为它们都只是引用相同的变量。但是,公共属性的使用有关现实世界的什么?

Obviously, in this example it doesn't make a difference, since they both just reference the same variable. But what about real world uses of Public Properties?

在一般情况下,做公益属性进行非常少,在这种情况下,它是可以给他们打电话?或者,人们把大量的功能集成到他们的公共属性不应由内部类的引用调用?

In general, do Public Properties perform very little, in which case it is OK to call them? Or do people put a lot of functionality into their Public Properties that should not be called by internal class references?

我看到在另一篇关于不把大量的功能集成到属性的东西,因为他们检查在调试器可以执行意想不到的效果。是真的吗?

I saw something in another post about NOT putting lots of functionality into Properties, since examining them in the Debugger can perform unexpected results. Is that true?

推荐答案

使用属性 - 可能的getter和setter方法​​应该适用范围内封装,甚至类自身内的任何逻辑。如果在干将内没有逻辑和setter它仍然不是安全使用领域的自己,因为如果在任何时候你想添加周围的进入这些领域的逻辑,你将不得不重构等等。

Use the property - any logic that may be encapsulated within the setters and getters ought to apply, even within the class itself. If there is no logic within the getters and setters it is still not safe to use the fields themselves because if at any point you wish to add logic around the access to those fields you will have to refactor much more.

这篇关于您是否使用数据成员或公共属性从类本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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