DDi*_*ita 4 c# linq linq-to-xml
当我尝试在BuildTypes方法中投射投影列表时,我得到一个空值列表.我也尝试过使用.Cast(),但是我得到一个错误,即某些属性无法转换.如果它有用,我可以发布错误.这是我的代码:
public class AuditActionType: EntityValueType
{
}
private List<T> BuildTypes<T>(XDocument xDocument) where T: EntityValueType
{
var types =
(from ty in xDocument.Descendants("RECORD")
select new
{
Id = GenerateGuid(),
Name = ty.Element("Name").Value,
EntityStatus = _activeEntityStatus,
DateCreated = DateTime.Now,
DateModified = DateTime.Now
} as T).ToList();
return types;
}
Run Code Online (Sandbox Code Playgroud)
所以我会这样称呼它:
var auditActorTypes = BuildTypes<AuditActorType>(auditActorTypesXml)
Run Code Online (Sandbox Code Playgroud)
我需要从XML文件中提取大量类型,并且不希望为每种类型重复代码.
您正在尝试将匿名对象转换为类型T
,这是无法完成的.匿名类型是它自己的唯一类型,与T
传入无关.
相反,您可以new()
在类型上提供约束T
以表示它需要默认构造函数,然后执行new T()
而不是创建新的匿名类型:
private List<T> BuildTypes<T>(XDocument xDocument) where T: EntityValueType, new()
{
var types =
(from ty in xDocument.Descendants("RECORD")
select new T()
{
Id = GenerateGuid(),
Name = ty.Element("Name").Value,
EntityStatus = _activeEntityStatus,
DateCreated = DateTime.Now,
DateModified = DateTime.Now
}).ToList();
return types;
}
Run Code Online (Sandbox Code Playgroud)
这是假设,当然,前提是Id
,Name
,EntityStatus
,DateCreated
,和DateModified
是基本的所有属性EntityValueType
.