简体   繁体   English

c#:getter/setter

[英]c#: getter/setter

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.我知道他们是 getter 和 setter,但想知道为什么字符串类型是这样定义的。 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:在 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 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.在功能上(并且就编译的 IL 而言),它们与具有支持字段的属性相同。

You can also use a lambda expression您还可以使用 lambda 表达式

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

With the release of C# 6, you can now do something like this for private properties.随着 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