2012-05-31 18 views
4

我有一個抽象父類,它從它繼承的子類。我有另一個類包含許多不同的子類的List<>類型。然後,我在另一個類中有一個方法,它的參數爲List<ParentType>,並且只調用聲明爲抽象的方法。List.Cast <>錯誤「是一種在給定的上下文中無效的方法」

我在使用List<T>.Cast<T2>在子類的列表上遇到問題。我得到的錯誤:

System.Linq.Enumerable.Cast(System.Collections.IEnumerable)' is a 'method', which is not valid in the given context

有沒有人知道如何解決這個錯誤?或者,我是否必須重建List<ParentType>類型的清單並逐個重新更新每個項目?我想要做的事: 公共抽象類P { public int num; public abstract double addSections(); }

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) { 
     //... 
    } 
} 
+7

你應該發佈給你這個錯誤的代碼。 –

+1

@保羅 - 的確如此。沒有語境,我們無法幫助你太多。 – bluevector

+0

增加了一些代碼 – David

回答

7

在代替真正看到你的代碼,所以我們可以解決這個問題,怎麼樣改變的方法來代替:如果您使用C#4和.NET 4

public void DoSomething<T>(IEnumerable<T> items) where T : ParentType 
{ 
    ... 
} 

或者,這要細,如IEnumerable<T>是協變的T在.NET 4

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()) 
+0

不幸的是我在這個項目上遇到了.NET 3.5。你的第一個例子工作,非常感謝!我不知道你可以在C#中編寫這樣的語法。 – David

2

現在你已經添加的代碼,我看到兩個潛在的問題:

  1. 您需要在調用Cast時添加括號。

    listA.Cast<P>()

    Cast是不是有些特殊的運算符,它就像任何其他的擴展方法。

  2. 那些調用helper實際上是在課堂上,而不是在另一種方法中?那也是一個問題。

+0

謝謝你指出這一點,是的助手是在同一個級別。我也會改變.Cast <>()調用。 – David

相關問題