【问题标题】:How to determine if an object implements IDictionary or IList of any type如何确定对象是否实现任何类型的 IDictionary 或 IList
【发布时间】:2012-10-23 08:19:08
【问题描述】:

假设我声明以下内容

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?

【问题讨论】:

  • @DaveZych,那么我该如何检测该项目使用任何泛型类型实现 IDictionary 或 IList?
  • 您以错误的方式使用IsAssignableFrom。这是真的:typeof(Dictionary&lt;string, string&gt;).IsAssignableFrom(new Dictionary&lt;string, string&gt;().GetType());
  • 请问使用场景?

标签: c# .net


【解决方案1】:
    private void CheckType(object o)
    {
        if (o is IDictionary)
        {
            Debug.WriteLine("I implement IDictionary");
        }
        else if (o is IList)
        {
            Debug.WriteLine("I implement IList");
        }
    }

【讨论】:

  • 它不起作用:new ExpandoObject() is IDictionary 返回false,他问它是否实现了IDictionary的任何实现
  • @elios264 尝试使用 IDictionary 和 IList 进行检查。
【解决方案2】:

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

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

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

【讨论】:

  • item.GetType() == typeof (IList&lt;&gt;) 还是假的,试试这个
  • 如果对象是像int/string 这样的值类型,这会中断,因为它们没有实现GetGenericTypeDefinition() 方法。
  • @dragos 如果有人按照答案中的指导检查IsGenericType,则不会。
【解决方案3】:

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

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

我认为应该这样做。

【讨论】:

    【解决方案4】:

    下面是一些在 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
    

    【讨论】:

      猜你喜欢
      • 2010-10-19
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 2011-08-23
      • 2010-11-09
      相关资源
      最近更新 更多