转换基地类型的列表,以继承类型的列表 [英] Converting a List of Base type to a List of Inherited Type
问题描述
我可以肯定,这个问题解决了将在previous问题提出来了一些东西,但我无法找到它。
有是在C#类,它作为一个参数一个基类的泛型列表的方法。我需要通过继承的类的列表,不知道究竟如何做到这一点。我在我的努力得到一个错误。下面是样本code说明了这:
大众A级
{
公共静态无效MethodC(列表< A>)
{
//做一些与此列表
}
}
公共B类:一
{
// B从A继承,A是基类
}// code利用上述方法
清单< B> listOfB =新的List< B>();
A.MethodC((名单< A>)listOfB); //错误:这不起作用
A.MethodC(listOfB.ToList< typeof运算(A)>()); //错误:这不起作用
A.MethodC(listOfB.ConvertAll< A>(typeof运算(A))); //错误:这不起作用
//我怎么能做到这一点?它应该是可能的,我觉得
请注意:这里是作为一个参考我最后的工作方法。我得到了一个更好的解决我的问题,但在技术上这不是一个问题的答案,因为我的问题是impropertly措辞。
公共静态数据表
ObjectCollectionToDataTable<&链表本身GT;
(列表<&链表本身GT; ObjectCollection),其中为Glist
:BaseBusinessObject
{
DataTable的RET = NULL; 如果(ObjectCollection!= NULL)
{
的foreach(在ObjectCollection变种B)
{ DataTable的DT = b.ToDataTable();
如果(RET == NULL)
RET = dt.Clone();
如果(dt.Rows.Count大于0)
ret.Rows.Add(dt.Rows [0] .ItemArray);
}
} 返回RET;
}
如果您有可用LINQ可以做
VAR ListOfA = ListOfB.Cast< A方式>()了ToList();
I would be certain that this question addresses something that would have been brought up in a previous question, but I was unable to find it.
There is a method in a C# class that takes as a parameter a generic List of a Base Class. I need to pass a list of an inherited class and do not know exactly how to do this. I am getting an error in my attempts. Below is sample code to illustrated this:
public class A
{
public static void MethodC(List<A>)
{
// Do Something here with the list
}
}
public Class B : A
{
// B inherits from A, A is the Base Class
}
// Code utilizing the above method
List<B> listOfB = new List<B>();
A.MethodC( (List<A>) listOfB ); // Error: this does not work
A.MethodC( listOfB.ToList<typeof(A)>() ); // Error: this does not work
A.MethodC( listOfB.ConvertAll<A>(typeof(A)) ); // Error: this does not work
// how can I accomplish this? It should be possible I would think
Note: Here is my final working Method as a reference. I got an even better solution to my problem, but technically it wasn't an answer to the question, since my question was phrased impropertly.
public static DataTable
ObjectCollectionToDataTable<GLIST>
(List<GLIST> ObjectCollection) where GLIST
: BaseBusinessObject
{
DataTable ret = null;
if (ObjectCollection != null)
{
foreach ( var b in ObjectCollection)
{
DataTable dt = b.ToDataTable();
if (ret == null)
ret = dt.Clone();
if (dt.Rows.Count > 0)
ret.Rows.Add(dt.Rows[0].ItemArray);
}
}
return ret;
}
If you have linq available you can do
var ListOfA = ListOfB.Cast<A>().ToList();
这篇关于转换基地类型的列表,以继承类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!