2023-06-02 09:00:01

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

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

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

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


当前回答

这些都是自动属性

这是另一种写带有支持字段属性的方式。

public class Genre
{
    private string _name;

    public string Name 
    { 
      get => _name;
      set => _name = value;
    }
}

其他回答

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

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

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.

属性就像一个层,它将私有变量与类的其他成员分开。从外界看来,属性只是一个字段,可以使用.Property访问属性

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName => $"{FirstName} {LastName}";
}

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName { get { return $"{FirstName} {LastName}"; } }
}

FullName是一个属性。有箭头的那个是捷径。从外部世界,我们可以像这样访问FullName:

var person = new Person();
Console.WriteLine(person.FullName);

调用者并不关心您如何实现FullName。但在类内部,你可以随心所欲地更改FullName。

查看微软文档以获得更详细的解释:

https://learn.microsoft.com/en-us/dotnet/csharp/properties

它是c#的一个自动实现的属性。

在Visual Studio中,如果你在一个类中定义了一个属性X,并且你只想将这个类用作一个类型,在构建项目之后,你会得到一个警告,说“字段X从未被赋值,并且总是有它的默认值”。

通过添加{get;设置;}到X属性,则不会得到此警告。

此外,在Visual Studio 2013及更高版本中,通过添加{get;设置;}你就可以看到对该属性的所有引用。