我将构建我的MVC Web应用程序,并创建了我的数据模型 我在网上找到了很多编译数据模型代码的方法。这是最简单的,只使用公共属性:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
但我也找到了一个使用私有变量和公共属性的版本,如下所示:
public class Person
{
private int id;
private string firstName;
private string lastName;
public int Id { get { return id; } set { id = value; } }
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
}
这两种数据模型有什么区别? 什么时候使用第一个或第二个更合适?
答案 0 :(得分:4)
这就像询问:自动属性和普通属性有什么区别。
自动属性:
正常属性
get
和set
答案 1 :(得分:2)
如果第一个示例编译器将为每个自动属性本身创建私有字段,但它们的行为完全相同。有关MSDN
的更多信息我建议使用第二种方法,因为您可以更好地控制property
的工作方式,但使用第一种方法并没有错。
答案 2 :(得分:0)
你拥有的fiest块是自动属性,并且在底层c#将被编译为类似于第二个块,所以在这种情况下没有区别。在这里看一下这些帖子:
C# 3.0 auto-properties - useful or not?
What are Automatic Properties in C# and what is their purpose?
Any reason to use auto-implemented properties over manual implemented properties?
如果您正在实现INotifyPropertyChanged
接口,那么您将需要使用传统方式,因为您将与setter中的属性进行交互,请参阅示例...