【发布时间】:2009-03-26 15:36:38
【问题描述】:
我可以肯定这个问题解决了之前问题中会提出的问题,但我找不到它。
C# 类中有一个方法将基类的通用列表作为参数。我需要传递一个继承类的列表,但不知道该怎么做。我在尝试中遇到错误。下面是示例代码来说明这一点:
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
注意:这是我的最终工作方法作为参考。我的问题得到了更好的解决方案,但从技术上讲,这不是问题的答案,因为我的问题措辞不当。
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;
}
【问题讨论】:
-
这和我给你的答案一样......
-
从技术上讲,这也是您最初提出的问题的答案! :)
标签: c# generic-list