C#字段是否为 [英] C# Fields to be or not

查看:59
本文介绍了C#字段是否为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#4.0中,我可以在属性上使用访问器,并且编译器会在与此匹配的背景下创建一个字段.

In c#4.0 i can use accessers on properties and the compiler creates a field under the hood matching this.

public string Name
{
    get;
    private set;
}



创建名称字段不是必需的吗?
还是我错过了任何事情?

谢谢,
/Johan



Isn''t creating a field for name unnecessary?
Or have i missed out anything?

Thanks,
/Johan

推荐答案

这称为自动或自动实施的属性 [ ^ ]-这是一种声明您不打算使用任何自定义处理的简单属性的方法.编译器会自动为您创建后备字段.
That is called an Automatic, or Auto-Implemented Property[^] - it is a way to declare a simple property that you do not intend to use any custom processing with. The compiler automatically creates the backing field for you.


如果您了解属性永远不会自己存储任何值,则没有必要.为了能够存储任何东西,属性必须有一个字段可以存储.属性实际上只是语法糖,用于将两个常用操作(获取和设置)组合到一个干净的接口中.

对于自动属性,.NET已为您创建创建一个字段以支持此属性的工作.如果没有,则您将无法在对象上存储任何值.
It isn''t unnecessary if you understand that properties never store any values by themselves. To be able to store anything, properties must have a field to do so. Properties are really just syntactic sugar for combining two common operations (get and set) into one clean interface.

For automatic properties, .NET has done the legwork for you of creating a field to back this property. If it didn''t, you couldn''t store any values on your object.


这是对属性的完全合理的构造.您可能只希望使用者对象能够获得属性的值,但不一定能够从外部来源设置属性的值.

许多.Net类都具有以这种方式定义的属性.
That''s a perfectly reasonable construct for a property. You may only want a consumer object to be able to get a property''s value, but not necessarily be able to set the property''s value from an external source.

Many .Net classes have properties defined in just such a way.


这篇关于C#字段是否为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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