我正在学习ASP。NET MVC和我可以阅读英文文档,但我真的不明白这段代码中发生了什么:
public class Genre
{
public string Name { get; set; }
}
这意味着什么:{get;设置;} ?
我正在学习ASP。NET MVC和我可以阅读英文文档,但我真的不明白这段代码中发生了什么:
public class Genre
{
public string Name { get; set; }
}
这意味着什么:{get;设置;} ?
当前回答
定义Private变量
在构造函数中加载数据
我已经创建了常量,并从常量加载数据到Selected List类。
public class GridModel
{
private IEnumerable<SelectList> selectList;
private IEnumerable<SelectList> Roles;
public GridModel()
{
selectList = from PageSizes e in Enum.GetValues(typeof(PageSizes))
select( new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
Roles= from Userroles e in Enum.GetValues(typeof(Userroles))
select (new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
}
public IEnumerable<SelectList> Pagesizelist { get { return this.selectList; } set { this.selectList = value; } }
public IEnumerable<SelectList> RoleList { get { return this.Roles; } set { this.Roles = value; } }
public IEnumerable<SelectList> StatusList { get; set; }
}
其他回答
这意味着,如果您创建类型为Genre的变量,您将能够将该变量作为属性访问
Genre oG = new Genre();
oG.Name = "Test";
属性就像一个层,它将私有变量与类的其他成员分开。从外界看来,属性只是一个字段,可以使用.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
这些都是自动属性
这是另一种写带有支持字段属性的方式。
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
这样的{得到;设置;}语法被称为自动属性,c# 3.0语法
必须使用Visual c# 2008 / csc v3.5或以上版本进行编译。 但是您可以编译低至. net Framework 2.0的输出(不需要运行时或类来支持此特性)。
它是一个所谓的auto属性,本质上是以下代码的简写(类似的代码将由编译器生成):
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}