C#获取器,设置器声明 [英] C# getters, setters declaration

查看:67
本文介绍了C#获取器,设置器声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复项:

为什么使用吸气剂和塞特剂?

C#3.0自动属性-是否有用?

按以下方式定义属性之间是否有区别-

Is there a difference between defining properties the following way -

// private, with getter & setter
private string fName;
public string Name
{
    get { return this.fName }
    set { this.fName = value }
}

// define as a Property
public string Name { get; set;}

据我所知,它看起来仅是一种样式偏好。我是否缺少某些东西?

As far as I can tell, it only looks like a stylistic preference. Am I missing something?

推荐答案

差异:


  • 第二种形式只能使用C#3或更高版本的编译器进行编译

  • 第二种形式不允许任何代码(即使在同一类中)也可以直接访问该字段,因为真实字段具有无法说出的名字

第二个版本是称为自动实现的属性 (或简称为自动属性)。它们是在C#3中引入的。如果您只编写看起来像第一个版本的代码(即不涉及逻辑),那么自动属性非常有用。您以后总是可以通过将其转换为第一种形式来添加逻辑。在源代码和二进制兼容性方面,所有代码都将与该更改兼容。

The second version is what's known as an automatically implemented property (or "automatic property" for short). They were introduced in C# 3. If you're only writing code which looks like the first version - i.e. there's no logic involved - then automatic properties are great. You can always add logic later by converting it into the first form. All your code will be compatible with that change, in both source and binary compatibility terms.

请注意,自动属性不允许允许您指定默认值,并且没有真正的只读自动属性(即没有getter的属性)。最接近的是带有私有设置器的公共获取器,例如

Be aware that automatic properties don't allow you to specify default values, and there's no such thing as a genuinely readonly automatic property (i.e. one without a getter). The closest you can come is a public getter with a private setter, e.g.

public string Name { get; private set; }

虽然不尽相同,但在许多情况下都足够接近。

It's not quite the same, but it's close enough in many situations.

这篇关于C#获取器,设置器声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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