2012-11-02 34 views
5

可以說,我聲明如下如何確定一個對象實現IDictionary的或任何類型的IList的

Dictionary<string, string> strings = new Dictionary<string, string>(); 
List<string> moreStrings = new List<string>(); 

public void DoSomething(object item) 
{ 
    //here i need to know if item is IDictionary of any type or IList of any type. 
} 

我已經嘗試使用:

item is IDictionary<object, object> 
item is IDictionary<dynamic, dynamic> 

item.GetType().IsAssignableFrom(typeof(IDictionary<object, object>)) 
item.GetType().IsAssignableFrom(typeof(IDictionary<dynamic, dynamic>)) 

item is IList<object> 
item is IList<dynamic> 

item.GetType().IsAssignableFrom(typeof(IList<object>)) 
item.GetType().IsAssignableFrom(typeof(IList<dynamic>)) 

所有這一切都返回假的!

那麼我如何確定(在這種情況下)項目實現IDictionary或IList?

+1

看看這個:[如何確定一個類型是否實現了一個特定的泛型接口類型](http://stackoverflow.com/questions/503263/how-to-determine-if-a-type -implements-a-specific-generic-interface-type) – Zbigniew

+0

@DaveZych,那麼我該如何去檢測該項目是否使用任何泛型來實現IDictionary或IList? – series0ne

+0

您正在使用'IsAssignableFrom'錯誤的方式。這是真的:'typeof(Dictionary )。IsAssignableFrom(new Dictionary ()。GetType());' – khellang

回答

8
private void CheckType(object o) 
    { 
     if (o is IDictionary) 
     { 
      Debug.WriteLine("I implement IDictionary"); 
     } 
     else if (o is IList) 
     { 
      Debug.WriteLine("I implement IList"); 
     } 
    } 
+0

+1簡單解決方案 –

+0

它不工作:new ExpandoObject()是IDictionary返回false,並詢問它是否實現了IDictionary的任何實現<,> – elios264

2

您可以使用非通用接口類型,或者如果您確實需要知道該集合是通用的,則可以使用不帶類型參數的typeof

obj.GetType().GetGenericTypeDefinition() == typeof(IList<>) 
obj.GetType().GetGenericTypeDefinition() == typeof(IDictionary<,>) 

良好的措施,你應該檢查obj.GetType().IsGenericType,以避免非通用類型的InvalidOperationException

+0

爲什麼downvote? – Jay

+0

'item.GetType()== typeof(IList <>)'仍然是false,試試這個 –

+0

'item is typeof(IList <>)'錯誤的語法,編譯錯誤 –

1

不知道這是否是你想要什麼,但你可以在項目類型使用GetInterfaces,然後看看是否有任何返回的列表是IDictionaryIList

item.GetType().GetInterfaces().Any(x => x.Name == "IDictionary" || x.Name == "IList") 

應該這樣做,我認爲。

相關問題