公共属性和私有成员 C# [英] Public Properties and Private Members C#

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

问题描述

只使用公共属性而不是使用公共属性访问私有变量有什么好处?

What are the benefits of only using public properties instead of using the public property to access a private variable?

例如

public int iMyInt { get; set; }

代替

private int myint;
public int iMyInt { get { return myint; } set { myint = value; } }

除了让 .NET 管理属性下的变量/内存之外,还有什么优点(或缺点)?

Other than letting .NET manage the variable / memory underneath the property, what are the advantages (or disadvantages for that matter)?

推荐答案

使用自动属性(第一个示例)需要较少的输入.

Using automatic properties (the first example) requires less typing.

强烈建议只有公共属性而不是公共字段.许多属性是私有字段的简单包装器.自动属性可为您节省手动创建属性和支持字段的时间和麻烦.

It is highly recommended to have only public properties and not public fields. Many properties are simple wrappers around private fields. Automatic properties save you the time and hassle of manually creating the property and backing field.

您提到的简单案例的自动和手动属性背后的实际代码应该几乎相同.

The actual code behind automatic and manual properties for the simple case you mentioned should be nearly identical.

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

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