2023-06-02 09:00:01

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

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

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

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


当前回答

属性就像一个层,它将私有变量与类的其他成员分开。从外界看来,属性只是一个字段,可以使用.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

其他回答

基本上,它是一个快捷方式:

class Genre{
    private string genre;
    public string getGenre() {
        return this.genre;
    }
    public void setGenre(string theGenre) {
        this.genre = theGenre;
    }
}
//In Main method
genre g1 = new Genre();
g1.setGenre("Female");
g1.getGenre(); //Female

属性就像一个层,它将私有变量与类的其他成员分开。从外界看来,属性只是一个字段,可以使用.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

它基本上是一种速记。你可以写公共字符串Name {get;设置;}就像在许多例子中一样,但你也可以这样写:

private string _name;

public string Name
{
    get { return _name; }
    set { _name = value ; } // value is a special keyword here
}

为什么使用它?它可以用来过滤对属性的访问,例如您不希望名称中包含数字。

让我给你们举个例子:

private class Person {
    private int _age;  // Person._age = 25; will throw an error
    public int Age{
        get { return _age; }  // example: Console.WriteLine(Person.Age);
        set { 
            if ( value >= 0) {
                _age = value; }  // valid example: Person.Age = 25;
        }
    }
}

它的官方名称是Auto-Implemented Properties,阅读(编程指南)是一个好习惯。 我还推荐教程视频c#属性:为什么使用“get”和“set”。

它是一个所谓的auto属性,本质上是以下代码的简写(类似的代码将由编译器生成):

private string name;
public string Name
{
    get
    {
        return this.name;
    }
    set
    {
        this.name = value;
    }
}

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

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