为什么我需要的是通过公共财产暴露私有字段? [英] Why do I need a private field that is exposed via public property?

查看:103
本文介绍了为什么我需要的是通过公共财产暴露私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从Java世界正在添加为主。因此,C#性能也好看。

I'm comming from Java world mainly. So, C# properties do look nice.

我知道,与C#3.0或以上,我可以使用自动属性。我更加喜欢。)

I know that with C# 3.0 or above I can use Automatic Properties. I like it even more :).

我的问题是关于一个(也许更老)代码,我可以看到这一点:

My question is about a (maybe older) code where I can see this:

   private int age;

   public int Age {

     get { return age; }
     set { age = value; }     
   }



为什么我需要私人领域的时代?什么?我真躲在这里

Why do I need the private field age? What I'm I really hiding here?

编辑:

我完全理解为吸气的需要,二传手。我提到我是从Java世界,并正在添加该做的一切的时候。

I completely understand the need for the getter and setter. I mentioned that I'm comming from Java world and doing this all the time.

我不明白,在C#3.0或以上的自动属性是语法糖。但也许我的问题有一个简单的答案。难道这意味着(波纹管C#3.0),酒店不持有任何价值。因此,它必须从其他字段中的值?

I do understand that Automatic Properties in C# 3.0 or above are syntatic sugar. But maybe my question has a simpler answer. Does it means that (bellow C# 3.0) the property doesn't hold any value. So it must get the value from some other field?

推荐答案

C#的旧版本没有自动属性,所以你不得不声明变量的性质的,好像行动你的榜样。这些天来,同样的代码可以表示为:

Older versions of C# didn't have automatic properties, so you had to declare your variables that the properties acted upon like in your example. These days, the same code could be expressed as:

public int Age { get; set; }



我认为回答你的问题。但是,如果你问为什么不只是公众诠释年龄;而让程序员直接设置在球场上的价值?,则:

I think that answers your question. However, if you are asking "why not just have public int Age; and let programmers set the value on the field directly?", then:

首先要保持想到的是,属性访问被编译成方法。这意味着,它有不同的ABI只从读/写一个类的成员变量,即使它可能语法看起来是一样的,如果你有:

First thing to keep in mind is that property accessors are compiled into methods. This means that it has a different ABI from just reading/writing to a class member variable, even though it may syntactically look the same as if you had:

class Fu {
  public int Age;
}



那么,这是什么意思是,如果在某一点的道路,您需要添加一些通知年龄场发生了变化 - 如果你正在使用的属性,你可以轻松地添加此通知逻辑属性setter不打破ABI

So, what this means is that if, at some point down the road, you need to add some notification that the Age field has changed - if you are using properties, you can easily add this notification logic to the property setter without breaking ABI.

public int Age {
  get { return age; }
  set { age = value; NotifySomeOtherCode (); }
}

如果您与公共领域的开始,后来将其更改为一个属性将改变ABI这是坏的任何程序(县),可能取决于你的装配。所以,最好是具有属性开始。

If you start off with a public field, then later changing it to a property will change the ABI which is bad for any program(s) that may depend on your assembly. So it's better to start off with properties.

希望我做意义......

Hopefully I'm making sense...

这篇关于为什么我需要的是通过公共财产暴露私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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