2016-04-14 77 views
0

我有一個返回類型爲IEnumerable<T>的方法,我需要在變量中捕獲此方法的輸出。我不能用var來聲明變量,因爲變量必須在我的try/catch塊之外聲明。那麼,我可以用什麼具體的類型來聲明我的變量,它會接受我方法的輸出IEnumerable<T>?下面是這種情況下的樣子:什麼樣的具體類型可以接受IEnumerable <T>

IEnumerable<string> CalleeMethod() {...} 

IEnumerable<string> CallerMethod() 
{ 
    List<string> temp = null; 
    try 
    { 
     temp = CalleeMethod(); 
    } 
    catch(Exception exception) 
    { 
     Debug.WriteLine(exception.GetBaseException().Message); 
    } 
    return temp; 
} 

這個例子不工作,因爲當我宣佈tempList<T>,我得到的錯誤:cannot convert IEnumerable<T> to List<T>。我知道我可以撥打電話.ToList(),或將CalleeMethod()的輸出投射到List<T>,但我想簡單地用一個具體的類型來定義temp變量,該類型可以保存IEnumerable<T>輸出CalleeMethod()而不必投射它。那麼,具體的Type可以聲明temp,因爲這不會拋出cannot convert...錯誤?

在此先感謝您的幫助!

+2

'IEnumerable的溫度= NULL;'? –

+0

有沒有具體的型號可以使用? –

+1

@TylerJones當然...沒有。你已經聲明'IEnumerable CalleeMethod',所以你可以使用的唯一類型是IEnumerable'或者它是父母,而不是孩子 –

回答

3

你試過IEnumerable<String>嗎?

+0

是的,我需要一個具體的類型,而不是一個接口。 –

+0

您沒有可以訪問的具體類型。順便說一下,接口也是類型。 – Joey

+1

@TylerJones你不會這樣做,除非你在你的問題中遺漏了極其相關的信息。根據你的要求,'IEnumerable '是正確的答案。如果你想要別的東西,問問你真的在做什麼。 – hvd

0

只是使用IEnumerable<string> temp = Enumerable.Empty<String>();

+0

非常酷!我不知道Enumerable.Empty() –

+0

這種方法還可以讓你使用'var' ... –

+2

@TylerJones非常混淆爲什麼這個建議比Chris Pitman更好/不同(因爲這個建立了額外的未使用的對象)...另外,如果你有R#'var' <->混凝土類型的轉換是一半點擊... ... –

0

@ hvd是正確的。我認爲你有一些概念交叉。 'IEnumerable T'與'IEnumerable string'不同。這是一個簡單的通用版本...

public class GenericTest 
{ 
    public IEnumerable<T> CalleeMethod<T>() where T : class 
    { 
     return new List<T>(); 
    } 
} 
[TestMethod] 
public void IEnumberableT() 
{ 
    var x = new GenericTest(); 
    IEnumerable<string> result = x.CalleeMethod<string>(); 
} 
相關問題