我正在学习ASP。NET MVC和我可以阅读英文文档,但我真的不明白这段代码中发生了什么:
public class Genre
{
public string Name { get; set; }
}
这意味着什么:{get;设置;} ?
我正在学习ASP。NET MVC和我可以阅读英文文档,但我真的不明白这段代码中发生了什么:
public class Genre
{
public string Name { get; set; }
}
这意味着什么:{get;设置;} ?
当前回答
它是一个所谓的auto属性,本质上是以下代码的简写(类似的代码将由编译器生成):
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
其他回答
这些都是自动属性
这是另一种写带有支持字段属性的方式。
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
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.
基本上,它是一个快捷方式:
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
这意味着,如果您创建类型为Genre的变量,您将能够将该变量作为属性访问
Genre oG = new Genre();
oG.Name = "Test";
Get set是属性的访问修饰符。 Get读取属性字段。 Set设置属性值。 Get类似于只读访问。 Set类似于只写访问。 要将属性用作读写,必须同时使用get和set。