2015-02-24 78 views
13

我在當前項目中進行了大量的反思,並且試圖提供一些幫助程序方法來保持一切整潔。檢查類型或實例是否實現IEnumerable而不考慮類型T

我想提供一對方法來確定一個類型或實例實現IEnumerable - 無論其類型T.這裏是我的時刻:

public static bool IsEnumerable(this Type type) 
{ 
    return (type is IEnumerable); 
} 

public static bool IsEnumerable(this object obj) 
{ 
    return (obj as IEnumerable != null); 
} 

當我測試他們使用:

Debug.WriteLine("Type IEnumerable: " + typeof(IEnumerable).IsEnumerable()); 
Debug.WriteLine("Type IEnumerable<>: " + typeof(IEnumerable<string>).IsEnumerable()); 
Debug.WriteLine("Type List:   " + typeof(List<string>).IsEnumerable()); 
Debug.WriteLine("Type string:  " + typeof(string).IsEnumerable()); 
Debug.WriteLine("Type DateTime:  " + typeof(DateTime).IsEnumerable()); 
Debug.WriteLine("Instance List:  " + new List<string>().IsEnumerable()); 
Debug.WriteLine("Instance string: " + "".IsEnumerable()); 
Debug.WriteLine("Instance DateTime: " + new DateTime().IsEnumerable()); 

我得到這個作爲結果:

Type IEnumerable: False 
Type IEnumerable<>: False 
Type List:   False 
Type string:  False 
Type DateTime:  False 
Instance List:  True 
Instance string: True 
Instance DateTime: False 

類型的方法做似乎根本沒有工作 - 我曾預計至少會有直接的System.Collections.IEnumerable匹配。

我知道字符串在技術上是可枚舉的,雖然有一些注意事項。理想情況下,在這種情況下,我需要幫助器方法返回false。我只需要定義的IEnumerable<T>類型的實例返回true。

我可能剛剛錯過了一些相當明顯的東西 - 任何人都可以指向正確的方向嗎?

+0

我不明白這個問題。很明顯爲什麼'typeof()'任何類型都不返回'true';你問的是_type object_是否實現了接口,而不是類型本身。也許你想'IsAssignableFrom()'?但是你認爲'string'不符合條件?它具有「定義的IEnumerable 」類型「。 – 2015-02-24 17:10:52

+0

是的,這是第一種類型的問題 - 我一直在尋找整天在類型和實例之間跳躍的反射巢,並且不止一點困惑! 'string'確實有資格,但在這種情況下,我確實需要排除它 - 這可能更多的是在這個階段命名方法。我想我會保持原樣,並添加另一個只需在字符串上鍵入檢查。 – Octopoid 2015-02-24 17:14:35

+0

同意@JeroenMostert ...「重複」是問一個類型是否正在實現'IEnumerable '使用反射,這是問一個類型是否正在實現'IEnumerable',這是一個不同的事情,需要不同的解決方案證明是由不同的接受答案) – Jcl 2015-02-24 17:48:57

回答

22

下面一行

return (type is IEnumerable); 

在問 「如果Type一個實例,typeIEnumerable」,這顯然是不。

你想要做的是:

return typeof(IEnumerable).IsAssignableFrom(type); 
+0

@Octopoid一個字符串實現'IEnumerable ',所以這是真的,因爲這就是你要求的 – Jcl 2015-02-24 17:13:11

+0

@Octopoid這是正確的行爲。 'string'是一個'IEnumerable ',它是'IEnumerable'。 – 2015-02-24 17:13:21

+0

是的,'string'確實有資格,但是在這種情況下我確實需要排除它 - 這可能更多的是在這個階段命名方法。我想我會保持原樣,並添加另一個只需在字符串上鍵入檢查。 – Octopoid 2015-02-24 17:15:29

2

除了Type.IsAssignableFrom(Type),你也可以使用Type.GetInterfaces()

public static void ImplementsInterface(this Type type, Type interface) 
{ 
    bool implemented = type.GetInterfaces().Contains(interface); 
    return implemented; 
} 

這樣的話,如果你想查詢多個接口,你可以很容易地修改ImplementsInterface採取多個接口。

相關問題