为什么我需要一个通过公共属性公开的私有字段? [英] Why do I need a private field that is exposed via public property?

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

问题描述

我主要来自 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?

我完全理解对 getter 和 setter 的需求.我提到我来自 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; }

我认为这回答了您的问题.但是,如果您要问为什么不直接使用 public int Age;而让程序员直接在字段上设置值?",那么:

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;
}

所以,这意味着,如果在未来的某个时刻,您需要添加一些关于 Age 字段已更改的通知 - 如果您正在使用属性,则可以轻松地将此通知逻辑添加到属性设置器中,而无需打破 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天全站免登陆