创建 LINQ 使用的自定义类时,它是纯变量还是应该始终是属性重要吗?
有什么区别
class Class1
{
public string prop1 { get; set; }
public string prop2 { get; set; }
public string prop3 { get; set; }
public string prop4 { get; set; }
}
这和这
class Class2
{
public string var1;
public string var2;
public string var3;
public string var4;
}
执行 LINQ 查询时,
... select new Class1{...}
... select new Class2{...}
what would be the difference between this
class Class1
{
public string prop1 { get; set; }
public string prop2 { get; set; }
public string prop3 { get; set; }
public string prop4 { get; set; }
}
and this
class Class2
{
public string var1;
public string var2;
public string var3;
public string var4;
}
when executing a LINQ query with
... select new Class1{...}
... select new Class2{...}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就 LINQ 而言,这并不重要,但如果您关心正确的面向对象设计,则应该使用属性。如果您没有在类型的状态(即字段)周围添加适当的封装,那么您将来就会给自己带来潜在的问题,因为您将无法验证或控制类型的状态,因为该类型的使用者将无法验证或控制类型的状态。无需使用适当的渠道(即属性或方法)即可自由地改变事物。
尽管如此,无论如何,LINQ 查询都可以正常工作。
This doesn't matter as far as LINQ is concerned but if you are concerned about proper object oriented design, you should use properties. If you don't add proper encapsulation around the state of your type (i.e. the fields) you are creating potential problems for yourself in the future as you will be unable to verify or control the state of your type since the consumers of this type will have free reign to change things without using proper channels (i.e. a property or method).
All of that being said, however, LINQ queries will work just fine either way.