2023-06-02 09:00:01

{get;设置;}语法在c# ?

我正在学习ASP。NET MVC和我可以阅读英文文档,但我真的不明白这段代码中发生了什么:

public class Genre
{
    public string Name { get; set; }
}

这意味着什么:{get;设置;} ?


当前回答

属性是用于封装数据的函数,并允许在每次检索或修改值时执行额外的代码。

c#不同于c++, VB。Net或Objective-C没有一个单独的关键字来声明属性,而是使用两个关键字(get/set)来给出一个简短的语法来声明函数。

But it is quite common to have properties, not because you want to run additional code when data is retrieved or modified, but because either you MIGHT want to do so in the future or there is a contract saying this value has to be a exposed as a property (C# does not allow exposing data as fields via interfaces). Which means that even the abbreviated syntax for the functions is more verbose than needed. Realizing this, the language designers decided to shorten the syntax even further for this typical use case, and added “auto” properties that don’t require anything more than the bare minimum, to wit, the enclosing braces, and either of the two keywords (separated by a semicolon when using both).

在VB。Net中,这些“auto”属性的语法与c#中的长度相同——属性X为字符串vs字符串X {get;Set;},两种情况下都是20个字符。它实现了这样的简洁,因为在正常情况下,它实际上需要3个关键字,而在auto属性的情况下,可以不需要其中的2个。

如果从这两者中删除更多,要么就必须添加一个新的关键字,要么就必须赋予符号或空白以意义。

其他回答

这是一个自动实现的属性。它基本上是在c#中为类创建属性的一种简便方法,而不必为它们定义私有变量。当获取或设置变量值时不需要额外的逻辑时,通常使用它们。

你可以在MSDN的自动实现属性编程指南上阅读更多。

The get/set pattern provides a structure that allows logic to be added during the setting ('set') or retrieval ('get') of a property instance of an instantiated class, which can be useful when some instantiation logic is required for the property. A property can have a 'get' accessor only, which is done in order to make that property read-only When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted. The intermediate variable is usually prefixed with an underscore. this intermediate variable is private in order to ensure that it can only be accessed via its get/set calls. See the answer from Brandon, as his answer demonstrates the most commonly used syntax conventions for implementing get/set.

当属性出现在右侧(RHS)时调用Get。 属性出现在左侧(LHS)时调用 的'='符号

对于自动实现的属性,后台字段在后台工作,不可见。

例子:

public string Log { get; set; }

而对于非自动实现的属性,支持字段是前面的,作为私有作用域变量可见。

例子:

private string log;

public string Log
{
    get => log;
    set => log = value;
}

另外,这里值得注意的是getter和setter可以使用不同的“支持字段”

它们是公共属性Name的访问器。

你可以使用它们在一个类型实例中获取/设置该属性的值。

这意味着,如果您创建类型为Genre的变量,您将能够将该变量作为属性访问

Genre oG = new Genre();
oG.Name = "Test";