访问成员在自己的类:使用(自动)属性或不? [英] Accessing members in your own class: use (auto)properties or not?

查看:107
本文介绍了访问成员在自己的类:使用(自动)属性或不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个问题作为一个社区维基,因为没有正确或错误的答案。我只是想知道社会是如何看待这一具体问题。

I've created this "question" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.

当你有一个实例变量的类,并且还创建了一些简单的getter和setter属性这些实例变量,你应该使用的属性你自己的类里面,或者你应该总是使用实例变量?

When you have a class with instance variables, and you also created properties that are simply getters and setters for these instance variables, should you use the properties inside your own class, or should you always use the instance variable?

拥有自动性能C#3.0中做这样的一个连。很难决定

Having auto-properties in C# 3.0 made this an even harder decision.

使用属性:

public class MyClass
{
    private string _name;

    // could be an auto-property of-course
    public string Name { get { return _name; } set { _name = value; } }

    public void Action()
    {
        string localVar = Name;
        // ...
        Name = "someValue";
        // ...
    }
}

使用实例变量:

public class MyClass
{
    private string _name;

    public string Name { get { return _name; } set { _name = value; } }

    public void Action()
    {
        string localVar = _name;
        // ...
        _name = "someValue";
        // ...
    }
}



(对于那些谁恨成员前缀,我道歉)

就个人而言,我总是用后者(实例变量),因为我觉得属性只应通过其他类,而不是自己使用。这就是为什么我主要是从汽车的属性远离为好。

Personally, I always use the latter (instance variables), because I feel that properties should only be used by other classes, not yourself. That's why I mostly stay away from auto-properties as well.

当然,事情的变化,当属性的setter(或getter)并不仅仅是包装实例多一点变量。

Of course, things change when the property setter (or getter) does a little more than just wrapping the instance variable.

是否有令人信服的理由来选择一个或其他?

Are there compelling reasons to pick one or the other?

推荐答案

这是一个相当常见的问题。这里是我的一篇文章,介绍了一些问题:

This is a fairly frequently asked question. Here's my article that describes some of the issues:

http://blogs.msdn.com/ericlippert/archive/2009/01/14/automatic-vs-explicit-properties.aspx

这篇关于访问成员在自己的类:使用(自动)属性或不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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