C# 将基本类型列表转换为继承类型列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/686305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a List of Base type to a List of Inherited Type
提问by stephenbayer
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:
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
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;
}
采纳答案by Quintin Robinson
If you have linq available you can do
如果你有 linq 可用,你可以做
var ListOfA = ListOfB.Cast<A>().ToList();
回答by Andrew Hare
You are addressing the lack of covariance in the current C# version. Here is one way of doing it:
您正在解决当前 C# 版本中缺乏协方差的问题。这是一种方法:
listOfB.Cast<A>();
回答by Daniel Earwicker
You cannot do that. To understand why it is not allowed, imagine what would happen if Add
was called on a List<Derived>
after it had been cast to a List<Base>
.
你不能这样做。要理解为什么它是不允许的,想象一下如果Add
在 aList<Derived>
被强制转换为a之后调用它会发生什么List<Base>
。
Also, the answers implying that C# 4.0 will be different are wrong. List will never be modified to allow you to do this. Only IEnumerable
will - because it does not allow items to be added to the collection.
此外,暗示 C# 4.0 会有所不同的答案是错误的。永远不会修改列表以允许您执行此操作。只会IEnumerable
- 因为它不允许将项目添加到集合中。
Update: The reason it works in the solution you've gone for is because you're no longer passing the same list. You're creating a whole new list which is a copy of the original. This is why I asked about modifying the list; if MethodC
makes changes to the number of items on the list, those changes would be made to a copy, not the original list.
更新:它在您所寻求的解决方案中起作用的原因是因为您不再传递相同的列表。您正在创建一个全新的列表,它是原始列表的副本。这就是我询问修改列表的原因;如果MethodC
对列表中的项目数量进行了更改,这些更改将更改为副本,而不是原始列表。
I think the ideal solution for you is as follows:
我认为您的理想解决方案如下:
public abstract class A
{
public void MethodC<TItem>(List<TItem> list) where TItem : A
{
foreach (var item in list)
item.CanBeCalled();
}
public abstract void CanBeCalled();
}
public class B : A
{
public override void CanBeCalled()
{
Console.WriteLine("Calling into B");
}
}
class Program
{
static void Main(string[] args)
{
List<B> listOfB = new List<B>();
A a = new B();
a.MethodC(listOfB);
}
}
Notice how, with this solution, you can pass a List<B>
directly to MethodC
without needing to do that weird conversion on it first. So no unnecessary copying.
请注意,使用此解决方案,您可以List<B>
直接将 a 传递给,MethodC
而无需先对其进行奇怪的转换。所以没有不必要的复制。
The reason this works is because we've told MethodC
to accept a list of anything that is derived from A
, instead of insisting that it must be a list of A
.
这样做的原因是因为我们已经告诉MethodC
接受从 派生的任何内容的列表A
,而不是坚持它必须是A
.
回答by Humble Rumble
Here is an answer that will exclude any objects in your list of the wrong type. This is a much safer way in my opinion:
这是一个答案,它将排除错误类型列表中的任何对象。在我看来,这是一种更安全的方法:
List<A> ListOfA = ListOfB.OfType<A>().ToList();
The OfType method will exclude items of the wrong derived class where as the Cast will throw an error.
OfType 方法将排除错误派生类的项目,因为 Cast 将引发错误。