c#: getter/setter

走远了吗. 提交于 2019-11-26 12:57:41

问题


I saw something like the following somewhere, and was wondering what it meant. I know they are getters and setters, but want to know why the string Type is defined like this. Thanks for helping me.

public string Type { get; set; }

回答1:


Those are Auto-Implemented Properties (Auto Properties for short).

The compiler will auto-generate the equivalent of the following simple implementation:

private string _type;

public string Type
{
    get { return _type; }
    set { _type = value; }
}



回答2:


That is an auto-property and it is the shorthand notation for this:

private string type;
public string Type
{
  get { return this.type; }
  set { this.type = value; }
}



回答3:


In C# 6:

It is now possible to declare the auto-properties just as a field:

public string FirstName { get; set; } = "Ropert";

Read-Only Auto-Properties

public string FirstName { get;} = "Ropert";



回答4:


public string Type { get; set; } 

Is no different then doing

private string _Type;

public string Type
{    
get { return _Type; }
set { _Type = value; }
}



回答5:


This means that the compiler defines a backing field at runtime. This is the syntax for auto implemented properties.

More Information: Auto-Implemented Properties




回答6:


Its a automatically backed property, basically equivalent to

private string type;
public string Type
{
   get{ return type; }
   set{ type = value; }
}



回答7:


These are called auto properties.

http://msdn.microsoft.com/en-us/library/bb384054.aspx

Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.




回答8:


I know this is an old question but with the release of C# 6, you can now do something like this for private properties.

public constructor()
{
   myProp = "some value";
}

public string myProp { get; }


来源:https://stackoverflow.com/questions/6709072/c-getter-setter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!