这些语句之间有什么区别 [英] what is the difference between these statements

查看:80
本文介绍了这些语句之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些语句之间有什么区别

what is the difference between these statements

1.

public class Pesron

{
private string _name;
private int _age;

public string Name { get; set; }
public int Age { get; set; }
}

2.

public class Pesron
{
private string _name;
private int _age;


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

public string Age
{
get { return _age; }
set { _age = value; }
}

}

推荐答案

前者使用自动属性-_name _age 字段未使用,因为编译器生成了它自己的后备字段.
第二个版本显式引用了您自己的后备字段.
The former uses automatic properties - the _name and _age fields are not used as the compiler generates it''s own backing fields.
The second version explicitly references your own backing fields.


第一个版本使用默认的get和set代码,并且不需要包括字段变量,因此您可以实际编写它是:

The first one uses the default get and set code, and you don''t need to include the field variables, so you can actually write it as:

public class Pesron

{
public string Name { get; set; }
public int Age { get; set; }
}



这将在编译时自动创建_Name和_Age变量,我相信如果您使用这些名称创建变量(大写字母很重要!),则会出现编译错误.

第二个只是手动等效项.如果您除了获取/设置变量外没有做任何事情,并且不需要直接访问私有成员,则第一个输入起来更方便.



This will create _Name and _Age variables automatically when it compiles and I believe if you made variables with those names (capitalization matters!) you''d get a compile error.

The second is just the manual equivalent. If you aren''t doing anything beyond getting/setting the variables, and you don''t need to access the private member directly, the first is just more convenient to type.


就IL而言,两个是相同的.通常,仅在需要在get或set代码中执行其他操作(例如执行NotifyPropertyChanged)时才使用backing字段.即使您希望拥有只读属性,您也可能会发现自动属性会起作用,因为您可以执行以下操作:

The two are identical as far as IL is concerned. Normally only use backing field if you need to do something extra in the get or set code, such as doing a NotifyPropertyChanged. Even when you want to have readonly properties you may find that the automatic properties will work because you can do something like this:

public string Name { get; private set; }


这篇关于这些语句之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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