我正在学习ASP。NET MVC和我可以阅读英文文档,但我真的不明白这段代码中发生了什么:
public class Genre
{
public string Name { get; set; }
}
这意味着什么:{get;设置;} ?
我正在学习ASP。NET MVC和我可以阅读英文文档,但我真的不明白这段代码中发生了什么:
public class Genre
{
public string Name { get; set; }
}
这意味着什么:{get;设置;} ?
当前回答
Get set是属性的访问修饰符。 Get读取属性字段。 Set设置属性值。 Get类似于只读访问。 Set类似于只写访问。 要将属性用作读写,必须同时使用get和set。
其他回答
这是一个自动实现的属性。它基本上是在c#中为类创建属性的一种简便方法,而不必为它们定义私有变量。当获取或设置变量值时不需要额外的逻辑时,通常使用它们。
你可以在MSDN的自动实现属性编程指南上阅读更多。
属性就像一个层,它将私有变量与类的其他成员分开。从外界看来,属性只是一个字段,可以使用.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#的一个自动实现的属性。
这意味着,如果您创建类型为Genre的变量,您将能够将该变量作为属性访问
Genre oG = new Genre();
oG.Name = "Test";
基本上,它是一个快捷方式:
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