C# 如果对象是通用列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/248903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:50:09  来源:igfitidea点击:

If object is Generic List

c#.netvb.netlistgenerics

提问by Dested

Is there any way to determine if an object is a generic list? I'm not going to know the type of the list, I just know it's a list. How can I determine that?

有没有办法确定一个对象是否是一个通用列表?我不知道列表的类型,我只知道它是一个列表。我怎么能确定呢?

采纳答案by Timothy Khouri

This will return "True"

这将返回“真”

List<int> myList = new List<int>();

Console.Write(myList.GetType().IsGenericType && myList is IEnumerable);

Do you care to know if it's exactly a "List"... or are you ok with it being IEnumerable, and Generic?

您是否想知道它是否完全是“列表”...或者您是否同意它是 IEnumerable 和 Generic?

回答by bioskope

Theres a GetType() function in the System.Object class. Have you tried that?

System.Object 类中有一个 GetType() 函数。你试过吗?

回答by Andrew Theken

Try:

尝试:

if(yourList.GetType().IsGenericType)
{
  var genericTypeParams = yourList.GetType().GetGenericArguments;
  //do something interesting with the types..
}

回答by Nathan Baulch

The following method will return the item type of a generic collection type. If the type does not implement ICollection<> then null is returned.

以下方法将返回泛型集合类型的项目类型。如果该类型未实现 ICollection<>,则返回 null。

static Type GetGenericCollectionItemType(Type type)
{
    if (type.IsGenericType)
    {
        var args = type.GetGenericArguments();
        if (args.Length == 1 &&
            typeof(ICollection<>).MakeGenericType(args).IsAssignableFrom(type))
        {
            return args[0];
        }
    }
    return null;
}

Edit:The above solution assumes that the specified type has a generic parameter of its own. This will not work for types that implement ICollection<> with a hard coded generic parameter, for example:

编辑:上述解决方案假定指定的类型具有自己的泛型参数。这不适用于使用硬编码泛型参数实现 ICollection<> 的类型,例如:

class PersonCollection : List<Person> {}

Here is a new implementation that will handle this case.

这是一个处理这种情况的新实现。

static Type GetGenericCollectionItemType(Type type)
{
    return type.GetInterfaces()
        .Where(face => face.IsGenericType &&
                       face.GetGenericTypeDefinition() == typeof(ICollection<>))
        .Select(face => face.GetGenericArguments()[0])
        .FirstOrDefault();
}

回答by Joe

The question is ambiguous.

这个问题是模棱两可的。

The answer depends on what you mean by a generic list.

答案取决于您所说的通用列表是什么意思。

  • A List<SomeType> ?

  • A class that derives from List<SomeType> ?

  • A class that implements IList<SomeType> (in which case an array can be considered to be a generic list - e.g. int[] implements IList<int>)?

  • A class that is generic and implements IEnumerable (this is the test proposed in the accepted answer)? But this will also consider the following rather pathological class to be a generic list:

  • 一个 List<SomeType> ?

  • 从 List<SomeType> 派生的类?

  • 一个实现 IList<SomeType> 的类(在这种情况下,数组可以被认为是一个通用列表 - 例如 int[] 实现 IList<int>)?

  • 一个通用并实现 IEnumerable 的类(这是在接受的答案中提出的测试)?但这也会将以下相当病态的类别视为通用列表:

.

.

public class MyClass<T> : IEnumerable
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        return null;
    }
}

The best solution (e.g. whether to use GetType, IsAssignableFrom, etc) will depend on what you mean.

最佳解决方案(例如是否使用 GetType、IsAssignableFrom 等)取决于您的意思。

回答by Stanislav Trifan

The accepted answer doesn't guarantee the type of IList<>. Check this version, it works for me:

接受的答案不保证 IList<> 的类型。检查这个版本,它对我有用:

private static bool IsList(object value)
{
    var type = value.GetType();
    var targetType = typeof (IList<>);
    return type.GetInterfaces().Any(i => i.IsGenericType 
                                      && i.GetGenericTypeDefinition() == targetType);
}