5

假设我声明以下内容

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?

4

4 回答 4

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");
        }
    }
于 2012-11-02T16:38:31.950 回答
4

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

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

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

于 2012-11-02T16:25:50.537 回答
1

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

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

我认为应该这样做。

于 2012-11-02T16:27:09.190 回答
0

以下是一些适用于 vb.net 框架 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
于 2020-08-31T22:34:38.707 回答