吸气剂应该看起来如何 [英] How getter should look

查看:67
本文介绍了吸气剂应该看起来如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在c#中看到了这种代码:

I have seen this kind of code in c#:

  private int id {get;set;}

但是我只会为该字段创建getter,因为如果有get和set方法,它与公共字段相同唯一的方法是:

but I would only create getter for the field cause if there is get and set for it is the same as public field is the only way is:

public int getId(){return id;}

如何在VS2010中自动自动生成吸气剂

How to automaticly generate only getters in VS2010

推荐答案

您实现的内容称为Automatic Property,它们看起来像这样:

What you have implemented is known as an Automatic Property they look like this:

private string Name { get; set; }

自动属性仅仅是语法糖,实际上,它们提供了一种简洁,快速的方法来实现此代码:

Automatic properties merely syntactical sugar and in reality, provide a succinct, quick way to implement this code:

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

您可以使用手动属性来忽略自动属性,而只需删除get.或使用自动属性,并通过用private access修饰符标记get,使属性的值对外部成员只读:

You could disregard automatic properties, using manual proeprties and simply remove the get. Or use automatic properties and make the property's value read only to external members by marking the get with the private access modifier:

public string Name { get; private set; }

您说过通常会使用的代码在C#中实际上并不需要,因为实际上,属性只是变相的方法,应该被用作更好的约定:

The code you say you would usually use, is never really needed in C# because properties, in reality are just methods in disguise and should be used as a better convention:

public int getId(){return id;} //bad

这篇关于吸气剂应该看起来如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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