我有一个抽象的父类,子类继承自它。我还有另一个类,其中包含不同子类的许多List<>
类型。然后,我在另一个类中有一个方法,该方法采用参数 List<ParentType>
并仅调用声明为抽象的方法。
我在子类列表中使用List<T>.Cast<T2>
时遇到问题。我收到错误:
System.Linq.Enumerable.Cast(System.Collections.IEnumerable)"是一个"方法",在给定的上下文中无效
有人知道如何解决此错误吗?还是必须重建类型 List<ParentType>
的列表并单独重铸每个项目?
我想做什么: 公共抽象类 P { 公共国际数字; 公共摘要双添加节(); }
public class A : P {
public int num2;
public A(int r, int n) {
num = r;
num2 = n;
}
public double addSections() { return (double)num + (double)num2; }
}
public class B : P {
public double g;
public B(int r, double k) {
num = r;
g = k;
}
public double addSections() { return (double)num + g; }
}
public class MyClass {
public MyClass() {
List<A> listA;
List<B> listB;
//...
helper(listA.Cast<P>()); //doesn't work
helper(listB.Cast<P>().ToList()); //doesn't work either
}
public void helper(List<P> list) {
//...
}
}
与其实际查看您的代码以便我们可以修复它,不如更改方法:
public void DoSomething<T>(IEnumerable<T> items) where T : ParentType
{
...
}
或者,如果您使用的是 C# 4 和 .NET 4,这应该没问题,因为IEnumerable<T>
在 .NET 4 中T
是协变的。
public void DoSomething(IEnumerable<ParentType> items)
{
...
}
你真的需要接受List<ParentType>
的方法吗?毕竟,如果您要致电:
var parentList = childList.Cast<ParentType>().ToList();
并将其传递给方法,那么无论如何,您已经有两个完全独立的列表。
顺便说一下,IEnumerable<T>
协变的另一个影响是,在 .NET 4 中,您可以避免Cast
调用,而只调用:
var parentList = childList.ToList<ParentType>();
编辑:现在您已经发布了代码,只需不调用Cast
方法作为方法:
// This...
helper(listB.Cast<P>.ToList())
// should be this:
helper(listB.Cast<P>().ToList())
现在您已经添加了代码,我看到了两个潜在的问题:
-
调用
Cast
时需要添加括号,例如listA.Cast<P>()
Cast
不是什么特殊的运算符,它是一种扩展方法,就像其他任何东西一样。 -
这些对
helper
的调用实际上是在类级别,而不是在另一个方法中?那也是一个问题。