如果您引用的属性或成员变量的类里面? [英] Should you reference the Property or the Member Variable inside a class?

查看:160
本文介绍了如果您引用的属性或成员变量的类里面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/271318/should-you-access-a-variable-within-the-same-class-via-a-property">Should您是通过属性访问同一个类中的变量?

我遇到了这个最近与很好奇,如果有某种标准,哪一个你应该引用而一个类中。

我是说真的不应该有所作为无论你直接访问成员变量或通过财产(除非你需要闪避一些自定义的setter code),但我想,以确保有没有它的最佳实践。

 部分MyClass类{
    私人字符串FOO;

    内部字符串富{
        得到 {
            返回FOO;
        }

        私人集合{
            富=价值;
            //我做其他的东西
        }
    }

    公共无效DoSomething的(){
        //选择1;
        富=一些字符串;

        //选择2;
        富=一些字符串;
    }
}
 

解决方案

这不应该是一个选择,你真的让。无论是code中设置器应该运行,在这种情况下使用的属性,或不是,在这种情况下使用的构件的变量。在最重要的条件之一是正确的,一个是错误的。也不是永远正确/错误在一般情况下,这是不寻常的是,以没有关系。

例如,如果二传手code被烧成改变事件,你希望收到通知的外部对象,它改变了,还是不行?如果你改变它在响应previous变化,可能不会(无限递归的人?)如果没有,你可能希望确保它的发射(让你不改变的价值,而不是通知任何人变化)。

如果它只是验证该被设置的值是有效的,则无论是要知道的是,在这种情况下,该值已经验证,并必须是有效的,在这种情况下,没有必要再次验证;设置该属性。如果您尚未验证你即将设置,那么你的需要的验证逻辑来​​运行,所以使用属性。

Possible Duplicate:
Should you access a variable within the same class via a Property?

I ran into this recently and was curious if there was some sort of standard for which one you should reference while inside a class.

I mean really it shouldn't make a difference whether you access the member variable directly or go through the property (unless you need to dodge some custom setter code), but I wanted to be sure there wasn't a best practice for it.

partial class MyClass {
    private string foo;

    internal string Foo {
        get {
            return foo;
        }

        private set {
            foo=value;
            // I do other stuff
        }
    }

    public void DoSomething() {
        //Option 1;
        Foo="some string";

        //Option 2;
        foo="some string";
    }
}

解决方案

This shouldn't be a choice you really make. Either the code in the setter is supposed to run, in which case use the property, or it's not, in which case you use the member variable. In most all situations one is right and one is wrong. Neither is always right/wrong in the general case, and it's unusual for it to "not matter".

For example, if the setter code is firing a "changed" event, do you want external objects to be notified that it changed, or not? If you're changing it in response to a previous change, probably not (infinite recursion anyone?) if no, you probably want to make sure it's fired (so that you're not changing a value and not notifying anyone of changes).

If it's just validating that the value being set is valid, then either you know that, in this context, the value is already validated and must be valid, in which case there is no need to validate again; set the property. If you haven't yet validated what you're about to set then you want the validation logic to run, so use the property.

这篇关于如果您引用的属性或成员变量的类里面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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