物业有和没有获得{;组; } [英] Property with and without { get; set; }

查看:96
本文介绍了物业有和没有获得{;组; }的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C#

是什么

public string MyValue;

public string MyValue { get; set; }



我一直认为两者都是一样的。事情并没有在我的代码工作。使用后一种形式使工作。但不知道有什么区别。你能帮忙吗?

I always assumed that both were same. Something was not working in my code. Using the latter form made it work. But don't know what is the difference. Can you help?

感谢

推荐答案

首先是一个公共场,第二个是自动实现的公共属性。

The first is a public field, the second an automatically implemented public property.

他们是不一样的。随着汽车实现的属性,编译器将生成一个私人支持字段。

They are not the same. With the auto implemented property the compiler will generate a private backing field.

虽然两者都可以作为一种方法来从你的类公开数据的工作,你应该使用下面的属性信息隐藏的原则 - 领域应该是私有的,只能通过属性进行访问。这使您可以进行更改执行不打破呼叫者。

Though both can work as a way to expose data from your class, you should be using properties following the principle of information hiding - fields should be private and only accessed through properties. This allows you to make changes to the implementation without breaking the callers.

这篇关于物业有和没有获得{;组; }的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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