C#泛型列表转换为类实现列表< T> [英] C# Generic List conversion to Class implementing List<T>

查看:160
本文介绍了C#泛型列表转换为类实现列表< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码产生的问题。




无法隐式转换类型'System.Collections.Generic.IEnumberable<数据字段<串GT;> 为数据域。一个显式转换存在(是否缺少强制转换?)。




我如何解决这个得到什么?什么?我做错了。



 公共类的Datafields:列表<&数据字段GT; 
{
}

公共抽象类的数据字段
{
公共字符串名称{;组; }
}

公共类数据字段< T> :数据字段
{
公众的T值{搞定;组; }
}

公共静态数据域ConvertXML(为XMLDocument数据){
的Datafields结果=(从XDocument.Parse D(data.OuterXML).Elements()
选择新的数据字段<串GT;
{
名称= d.Name.ToString(),
值= d.Value
})了ToList()。
返回结果;
}



编辑:移动下面的另一个问题的信息



使用LINQ to创建一个列表< T>其中T:SomeClass的< U>



另外,我想能够做这样的事在此声明如下,以设置类型的每个的值。我怎样才能做到这一点。



 选择新的数据字段< [元素的属性类型称为> 
{
名称= d.Name.ToString(),
值= d.Value
}


解决方案

下面的构造函数添加到数据域

 公共类的Datafields:列表<&数据字段GT; {
公共数据域():基地(){}
公共数据域(IEnumerable的<数据字段>项目):基地(项目){}
}

然后

 公共静态数据域ConvertXML(的XMLDocument数据){
变种结果=(BLAH ..)了ToList();
返回新的数据域(结果);
}


The following code produces the issue

Cannot implicitly convert type 'System.Collections.Generic.IEnumberable<DataField<string>>' to 'DataFields'. An explicit conversion exists (are you missing a cast?).

How do I get around this? What am I doing wrong?

public class DataFields : List<DataField>
{
}

public abstract class DataField
{
    public string Name { get; set; }
}

public class DataField<T> : DataField
{
    public T Value { get; set; }
}

public static DataFields ConvertXML(XMLDocument data) {
    DataFields result = (from d in XDocument.Parse(data.OuterXML).Elements()
                      select new DataField<string>
                      {
                          Name = d.Name.ToString(),
                          Value = d.Value
                      }).ToList();
    return result;
}

Edited: Moving the information below to another question.

Using LINQ to create a List<T> where T : someClass<U>

In addition I would like to be able to do something like the following in this statement, in order to set the type of the value for each. How can I accomplish this.

select new DataField<[Attribute of element called type]>
{
  Name = d.Name.ToString(),
  Value = d.Value
}

解决方案

Add the following constructor to the DataFields class

public class DataFields : List<DataField> {
    public DataFields() : base() {}
    public DataFields(IEnumerable<DataField> items) : base(items){}
}  

Then

public static DataFields ConvertXML(XMLDocument data) {      
    var result = (BLAH..).ToList();      
    return new DataFields(result);     
}  

这篇关于C#泛型列表转换为类实现列表&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆