C#-如何使用LINQ to对象创建不可变对象
我通过解析XDocument中的值来创建一个具有LINQ的对象。我的理解是,除非以后确实需要更改值,否则对象应该被创建为不可变的,所以我创建了私有setterC#-如何使用LINQ to对象创建不可变对象,c#,xml,linq,immutability,C#,Xml,Linq,Immutability,我通过解析XDocument中的值来创建一个具有LINQ的对象。我的理解是,除非以后确实需要更改值,否则对象应该被创建为不可变的,所以我创建了私有setter public class GeoLookupResult { public string LocationType { get; private set; } public string Country { get; private set; } public string CountryIso3166 { get
public class GeoLookupResult
{
public string LocationType { get; private set; }
public string Country { get; private set; }
public string CountryIso3166 { get; private set; }
public GeoLookupResult(string locationType, string country, string countryIso3166)
{
this.LocationType = locationType;
this.Country = country;
this.CountryIso3166 = countryIso3166;
}
}
但是,我似乎无法使用LINQ to Objects来创建具有这样构造函数的对象(因为“GeoLookupResult不包含'locationType'的定义”等):
有没有一种方法可以像这样使用构造函数?或者我应该放弃不变性的概念,只使用公共属性设置器并在LINQ查询中使用它们?(例如:
LocationType=(string)i.Element(“location”).Element(“type”)
我不能完全确定你的问题是否正确,但你试过了吗
var query = from i in document.Descendants("response")
select new GeoLookupResult(
(string)i.Element("location").Element("type"),
(string)i.Element("location").Element("country"),
(string)i.Element("country_iso3166")
);
通过这种方式,您可以使用三个参数调用
GeoLookupResult
类的已定义构造函数。按照当前的方式,它尝试调用默认构造函数,然后通过它们的setter(声明为private)分配所提供的属性。当然,您可以使用自己的构造函数。在您的li中nq select语句您所使用的被称为对象初始值设定项
一个带有新GeoLookupResult{..}
的语句。它主要用于不想强制使用构造函数初始化类的对象时
因此,您应该调用自己的构造函数,而不是对象初始值设定项
var query = from i in document.Descendants("response")
select new GeoLookupResult(
(string)i.Element("location").Element("type"),
(string)i.Element("location").Element("country"),
(string)i.Element("country_iso3166")
);
您提到的构造函数不是OOP构造函数,而是一种对象初始化机制(C#编译器语法糖),有助于填充对象的公共属性和字段。
如果你坚持让你的对象不可变,你应该使用构造函数/工厂方法让其他组件创建你的对象。(左边绿色勾号)谢谢!
var query = from i in document.Descendants("response")
select new GeoLookupResult(
(string)i.Element("location").Element("type"),
(string)i.Element("location").Element("country"),
(string)i.Element("country_iso3166")
);