【问题标题】:Check if object is a System.Generic.List<T>, for any T [duplicate]检查对象是否是 System.Generic.List<T>,对于任何 T [重复]
【发布时间】:2017-10-16 13:58:02
【问题描述】:

示例代码:

    using System.Collections.Generic;
    ...

        // could return anything. 
        private object GetObject(int code)
        {
            object obj = null;

            if (code == 10)
            {
                var list1  = new List<Tuple<int, string>>();
                list1.Add(new Tuple<int, string>(2, "blah"));
                obj = list1;                
            }
            else if (code == 20)
            {
                obj = "hello";
            }
            else if (code == 30)
            {
                var list2 = new List<string>();
                list2.Add("o");
                obj = list2; 
            }
            // else etc, etc. 

            return obj; 
    }

    private bool DoAction(int code)
    {
        object obj = GetObject(code);

        bool isListT = ??? 
        return isListT;    
    }

在上面的代码中,GetObject 可以返回任何类型的对象。 在 DoAction 内部,在调用 GetObject 之后,我希望能够判断返回的 obj 是否是 System.Collections.Generic.List&lt;T&gt; 的任何类型。我不在乎(也不可能知道)T 是什么。所以 DoAction(10) 和 DoAction(30) 应该返回 true,而 DoAction(20) 应该返回 false。

【问题讨论】:

  • 如果你这样做,它可能会起作用 if (yourVar is List)
  • @Arthur:这行不通。不过,也许(obj is IList) 就足够了。
  • @Achilles: System.Object 没有实现IEnumerable
  • 不是您问题的重点,但我建议将您的链式 if 语句更改为 switch 语句。其次,再次提示比实际解决方案更多:如果您返回一个对象,您应该能够使用返回的值,就好像它是一个对象一样。 通常是糟糕设计的标志;尽管确实会发生(例如,从控件中检索绑定项目时,因为可以将任何对象强制转换为其中)。但是,我认为返回一个可以是可枚举或单个对象的对象几乎没有用处。
  • 我同意@Flater,你做错了什么(从 OOP 的角度来看)。我相信你是XY problem 的受害者,也许你可以问一个不同的问题,说明你到底想要做什么。

标签: c# generics .net-4.5


【解决方案1】:

您可以使用Type.GetGenericTypeDefinition

object obj = GetObject(code);
Type type = obj?.GetType();
bool isList = type != null 
           && type.IsGenericType 
           && type.GetGenericTypeDefinition() == typeof(List<>);

【讨论】:

  • 谢谢。在 C# 4.5 中,我最终选择了: obj != null && obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(List)
  • @MoeSisko:谢谢,修改答案以添加 IsGenericType 检查
【解决方案2】:

这应该可以工作

private static bool DoAction(int code)
{
    object obj = GetObject(code);

    return obj is IList;
}

然后:

var first = DoAction(10);   //true
var second = DoAction(20);  //false
var third = DoAction(30);   //true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 2018-03-09
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2015-02-22
    相关资源
    最近更新 更多