2012-04-15 51 views
0

我有此代碼以獲得「A」作爲過濾結果。OfType <????>當在C#中使用方法的參數

public static void RunSnippet() 
{ 
    Base xbase = new Base(); 
    A a = new A(); 
    B b = new B(); 
    IEnumerable<Base> list = new List<Base>() { xbase, a, b }; 
    Base f = list.OfType<A>().FirstOrDefault(); 
    Console.WriteLine(f); 
} 

我需要使用IEnumerable<Base> list = new List<Base>() {xbase, a, b};從功能如下:

public static Base Method(IEnumerable<Base> list, Base b (????)) // I'm not sure I need Base b parameter for this? 
{ 
    Base f = list.OfType<????>().FirstOrDefault(); 
    return f; 
} 

public static void RunSnippet() 
{ 
    Base xbase = new Base(); 
    A a = new A(); 
    B b = new B(); 
    IEnumerable<Base> list = new List<Base>() { xbase, a, b }; 
    //Base f = list.OfType<A>().FirstOrDefault(); 
    Base f = Method(list); 
    Console.WriteLine(f); 
} 

我在使用什麼參數 '????'從原始代碼中獲得相同的結果?

+5

你不能調用'Method(list)' - 'list'不是'Base',它是'IEnumerable '。這是你第二次犯這個錯誤 - 你用IEnumerable ''有多舒服?並且'Method' *總是*意味着返回一個'A'值?如果是這樣,爲什麼它會聲明返回'Base',爲什麼不能使用'A'而不是'''? – 2012-04-15 20:31:18

+0

@Jon:Method()的參數應該是'IEnumerable list,Base b'。對於????,我需要從第二個參數中獲得類型A.我嘗試使用(Base b)作爲參數,並在中使用b.GetType(),但它不起作用,因爲b.GetType()返回Type not base。 – prosseek 2012-04-15 20:40:54

回答

4

看起來好像你正在尋找一種通用的方式來做Method什麼是基於Base不同的兒童類型。你可以做到這一點:

public static Base Method<T>(IEnumerable<Base> b) where T: Base 
{ 
    Base f = list.OfType<T>().FirstOrDefault(); 
    return f; 
} 

這將從bT類型(必須的Base一個孩子)的返回的第一個實例。

+1

請注意,雖然這被接受,但它不符合實際要求的問題 - 即從參數值中獲取類型。這是一個有點混亂的問題,無可否認...... – 2012-04-15 20:48:12

+1

我的原始答案遠不如他們所要求的,並且顯然是正確的。這是我試圖做一些有用的嘗試。希望它確實有幫助。 :) – 2012-04-15 20:51:09

+0

@ M.Babcock - 這正是我想要的。謝謝。 – prosseek 2012-04-16 16:19:41

2

如果要在一個類型的查詢,你可以嘗試這樣的事:

public static Base Method(IEnumerable<Base> list, Type typeToFind) 
{ 
    Base f = (from l in list 
     where l.GetType()== typeToFind 
       select l).FirstOrDefault(); 
    return f; 
} 

如果它不是你要搜索的內容,請澄清。

+0

@ M.Babcock:你的意思是OfType,還是typeof? – 2012-04-15 20:44:37

+1

這不就是'OfType '已經做了什麼? – 2012-04-15 20:45:37

+0

@JonSkeet - 編輯(或者轉發,因爲我沒有及時趕上)。 – 2012-04-15 20:46:01