属性VS公共成员变量 [英] Properties vs Public member variables

查看:117
本文介绍了属性VS公共成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
是什么领域,在C#一个属性之间的区别

Possible Duplicate:
What is the difference between a field and a property in C#

我是一个程序员开始,我读过所有关于类属性。书指出属性可以间接访问成员变量。好了,是什么使得它有什么不同不仅仅是让业界人士和直接访问它。

I'm a beginning programmer and I've read all about class properties. Books state that properties allow you to indirectly access member variables. Ok, so what makes it any different than just making the field public and accessing it directly?

下面是由杰西自由学习C#3.0的报价:

Here's a quote from Learning C# 3.0 by Jesse Liberty:

例如,您可能需要外部
类能够读取值,但不能改变它;或者你可能想要写
的一些代码,使内部磁场可以在一定范围内仅接受值。如果美元的成员字段b $ B授予外部类自由出入,你无法控制任何。

For example, you might want external classes to be able to read a value, but not change it; or you might want to write some code so that the internal field can accept only values in a certain range. If you grant external classes free access to your member fields, you can’t control any of that.

我不不懂他在这里说。有人能进一步解释这或给的,为什么我想在做现场市民使用属性的例子。正如我现在明白了它,他们都将完成同样的事情......所以我显然失去了一些东西。

I don't understand what he is saying here. Can someone further explain this or give an example of why I would want to use a property over making the field public. As I understand it now they would both accomplish the same exact thing...so I'm obviously missing something here.

推荐答案

属性可以有副作用,它们提供围绕吸气和二传手方法的语法糖。

Properties can have side-effects, They provide syntactic sugar around 'getter' and 'setter' methods.

public class MyClass {

   int sizeValue = 0;

   public int Size {
      get {
         return sizeValue;
      }
      set {
         if ( value < 10 ) throw new Exception("Size too small");
         sizeValue = value;
      }
   }
}



属性也可以有不同的层次get和set的保护,你不能做到这一点与领域。

Properties can also have different levels of protection for get and set, you cannot do that with fields.

public class MyOtherClass {

   // only this object can set this.
   public int Level {
      get; private set; 
   }

   // only things in the same assembly can set this.
   public string Name {
      get; internal set;
   }
}

这篇关于属性VS公共成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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