簡體   English   中英

c#:getter/setter

[英]c#: getter/setter

我在某處看到類似下面的內容,想知道它是什么意思。 我知道他們是 getter 和 setter,但想知道為什么字符串類型是這樣定義的。 謝謝你幫助我。

public string Type { get; set; }

這些是自動實現的屬性(簡稱自動屬性)。

編譯器將自動生成以下簡單實現的等效項:

private string _type;

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

這是一個自動屬性,它是它的簡寫符號:

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

在 C# 6 中:

現在可以將自動屬性聲明為字段:

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

只讀自動屬性

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

和做沒有什么不同

private string _Type;

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

這意味着編譯器在運行時定義了一個支持字段。 這是自動實現屬性的語法。

更多信息: 自動實現的屬性

它是一個自動支持的屬性,基本上相當於:

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

這些稱為自動屬性。

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

在功能上(並且就編譯的 IL 而言),它們與具有支持字段的屬性相同。

您還可以使用 lambda 表達式

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

隨着 C# 6 的發布,您現在可以對私有財產執行類似的操作。

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

public string myProp { get; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM