2023-06-02 09:00:01

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

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

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

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


当前回答

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.

其他回答

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

这是一种将数据成员公开为公共的快捷方式,这样您就不需要显式地创建私有数据成员。c#将为您创建一个私有数据成员。

您可以不使用此快捷方式将数据成员设为公共,但如果您决定更改数据成员的实现以具有某些逻辑,则需要破坏接口。因此,简而言之,它是创建更灵活代码的捷径。

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

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

基本上它有助于保护你的数据。考虑这个没有setter和getter的例子,以及有它们的同一个例子。

没有setter和getter

类学生

using System;
using System.Collections.Generic;
using System.Text;

namespace MyFirstProject
{
    class Student
    {
        public string name;
        public string gender;
        public Student(string cName, string cGender)
        {
            name = cName;
            gender= cGender;
        }

     }
}

在主

 Student s = new Student("Some name", "Superman"); //Gender is superman, It works but it is meaningless
 Console.WriteLine(s.Gender);

使用setter和getter

using System;
using System.Collections.Generic;
using System.Text;

namespace MyFirstProject
{
    class Student
    {
        public string name;
        private string gender;
        public Student(string cName, string cGender)
        {
            name = cName;
            Gender = cGender;
        }

        public string Gender
        {
            get { return gender; }
            set
            {
                if (value == "Male" || value == "Female" || value == "Other")
                {
                    gender = value;
                }
                else
                {
                    throw new ArgumentException("Invalid value supplied");
                }
            }
        }
    }
}

主要:

  Student s = new Student("somename", "Other"); // Here you can set only those three values otherwise it throws ArgumentException.
Console.WriteLine(s.Gender);

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

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

例子:

public string Log { get; set; }

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

例子:

private string log;

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

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