如何确定对象是否实现任何类型的IDictionary或IList

时间:2012-11-02 16:21:09

标签: c# .net

假设我宣布以下内容

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>))

所有这些都返回false!

那么我如何确定(在此上下文中)项目实现IDictionary还是IList?

4 个答案:

答案 0 :(得分: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");
        }
    }

答案 1 :(得分:3)

您可以使用非泛型接口类型,或者如果您确实需要知道该集合是通用的,则可以使用不带类型参数的typeof

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

为了更好地衡量,您应该检查obj.GetType().IsGenericType以避免使用InvalidOperationException非泛型类型。

答案 2 :(得分:1)

不确定这是否是您想要的,但您可以在项目类型上使用GetInterfaces,然后查看是否有任何返回的列表IDictionaryIList

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

我认为应该这样做。

答案 3 :(得分:0)

以下是一些布尔函数,可在vb.net Framework 2.0中使用通用接口类型:

Public Shared Function isList(o as Object) as Boolean
    if o is Nothing then return False
    Dim t as Type = o.GetType()
    if not t.isGenericType then return False
    return (t.GetGenericTypeDefinition().toString() = "System.Collections.Generic.List`1[T]")
End Function

Public Shared Function isDict(o as Object) as Boolean
    if o is Nothing then return False
    Dim t as Type = o.GetType()
    if not t.isGenericType then return False
    return (t.GetGenericTypeDefinition().toString() = "System.Collections.Generic.Dictionary`2[TKey,TValue]")
End Function