OO设计 - 你使用公共属性或私有字段内部? [英] OO Design - do you use public properties or private fields internally?

查看:112
本文介绍了OO设计 - 你使用公共属性或私有字段内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作在C#2.0,但是这将适用于大多数面向对象的语言。当我创建具有公共属性类,包装私有字段,切换回&安培;之间来回我是否应使用属性或字段内部。当然,C#3.0使得这更容易自动属性,但它仍然适用。



有什么关系?



 公共类Person 
{
私人字符串_name =;

公共字符串名称
{
{返回_name; }
集合{_name =价值; }
}

公众人物(字符串名称)
{
_name =名称; //我应该使用属性或此处字段?
}
}


解决方案

基本上,因为你可以实现在属性的验证和其他逻辑,就应该通过属性访问,除非你有特别的理由不这么做。



它有助于内的一致性的对象,因为这样,你知道你的私有字段的值已通过你选择把你的访问或setter方法​​任何苛刻了。



在另一方面,构造函数都不可能是一个例外,因为你可能需要设置的初始值。



但在一般情况下,我会说通过属性的访问。



修改



A(琐碎/做作)的例子

 公共类Person 
{
私人字符串_name =;
私有列表<串GT; oldnames =新的ArrayList();

公共字符串名称
{
{返回_name; }

{
oldnames.Add(_name);
_name =价值;
}
}

公众人物(字符串名称)
{
_name =名称; //我应该使用属性或此处字段?
}
}



因此​​,在这种情况下,你会想构造函数跳过财产,但如果你再次使用该字段,你会在你的代码造成的错误,因为你跳过了名归档。把验证你的财产的原因是,这样你就不用复制在每一个访问田间地头验证代码,所以你不应该跳过它,即使在私有方法。


I'm working in C# 2.0, but this would apply to most object oriented languages. When I create classes with public properties that wrap private fields, I switch back & forth between whether I should use the property or field internally. Of course C# 3.0 makes this easier with auto-properties, but it could still apply.

Does it matter?

public class Person
{
    private string _name = "";

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

    public Person(string name)
    {
        _name = name; //should I use the property or field here?
    }
}

解决方案

Basically, because you can implement your validation and other logic in the property, you should access through the property unless you have a specific reason not to.

It helps with consistency within your object, because that way you know that the values of your private fields have gone through whatever rigors you choose to put in your accessor or setter methods.

On the other hand, the constructor can possibly be an exception to this, because you might want to set initial values.

But in general, I'd say access through the property.

EDIT

A (trivial/contrived) example

public class Person
{
    private string _name = "";
    private List<String> oldnames = new ArrayList();

    public string Name
    {
        get { return _name; }
        set 
        {
           oldnames.Add(_name);
           _name = value; 
        }
    }

    public Person(string name)
    {
        _name = name; //should I use the property or field here?
    }
}

So in this case, you would want the constructor to skip the property but if you EVER use the field again you'll be causing a bug in your code because you're skipping the 'name archiving'. The reason to put validation in your property is so that you don't need to duplicate the validation code in every place that you access the field, so you shouldn't skip it even in private methods.

这篇关于OO设计 - 你使用公共属性或私有字段内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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