开发者

c#: getter/setter

开发者 https://www.devze.com 2023-03-20 09:25 出处:网络
I saw something like the following somewhere, and was wondering what it meant. I know they are getters and setters, but开发者_StackOverflow中文版 want to know why the string Type is defined like this.

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

public string Type { get; set; }


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; }
}


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; }
}


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";


public string Type { get; set; } 

is no different than doing

private string _Type;

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


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

More Information: Auto-Implemented Properties


It's an automatically backed property, basically equivalent to:

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


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.


You can also use a lambda expression

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


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; }
0

精彩评论

暂无评论...
验证码 换一张
取 消