公共变量与VS访问私有变量

公共变量与VS访问私有变量

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

问题描述

有其他人看到有人这样做:

Has anyone else seen people do this:

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

我了解使用访问,如果你要行使某种控制权,它被如何设置或当有一个get执行某种它的功能。但是,如果你只是要做到这一点,为什么不把这些变量公众开始?我缺少的东西吗?

I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to do this, why not just make the variable public to begin with? Am I missing something?

推荐答案

如果您成员公共字段,那么你就不能以后它重构为一个属性不改变接口类。如果你从一开始就公开为属性,你可以做任何更改,你需要和属性访问器的功能类的接口保持不变。

If you make the member a public field, then you can't later refactor it into a property without changing the interface to your class. If you expose it as a property from the very beginning, you can make whatever changes to the property accessor functions that you need and the class's interface remains unchanged.

请注意,随着C#3.0,你可以实现一个属性,而无需创建一个支持字段,例如:

Note that as of C# 3.0, you can implement a property without creating a backing field, e.g.:

public string Name { get; set; }

这将删除的是pretty多不实施公共领域摆在首位的属性的唯一理由。

This removes what is pretty much the only justification for not implementing public fields as properties in the first place.

这篇关于公共变量与VS访问私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:33