Тестирование, если объект имеет универсальный тип в C #

Из Swift2.0 Apple говорит:

«Всегда задавать свойства типа префикса со статическим ключевым словом, когда вы определяете их в протоколе. Это правило относится даже к тому, что требования к свойствам типа могут иметь префикс класса или статическое ключевое слово при реализации классом: «

124
задан Mehrdad Afshari 11 June 2009 в 17:34
поделиться

3 ответа

Если вы хотите проверить, является ли он экземпляром универсального типа:

return list.GetType().IsGenericType;

Если вы хотите проверить, является ли он универсальным List :

return list.GetType().GetGenericTypeDefinition() == typeof(List<>);

Как указывает Джон, это проверяет точную эквивалентность типов. Возврат false не обязательно означает, что список List возвращает false (т. Е. Объект не может быть назначен в List переменная).

183
ответ дан 24 November 2019 в 00:44
поделиться

I assume that you don't just want to know if the type is generic, but if an object is an instance of a particular generic type, without knowing the type arguments.

It's not terribly simple, unfortunately. It's not too bad if the generic type is a class (as it is in this case) but it's harder for interfaces. Here's the code for a class:

using System;
using System.Collections.Generic;
using System.Reflection;

class Test
{
    static bool IsInstanceOfGenericType(Type genericType, object instance)
    {
        Type type = instance.GetType();
        while (type != null)
        {
            if (type.IsGenericType &&
                type.GetGenericTypeDefinition() == genericType)
            {
                return true;
            }
            type = type.BaseType;
        }
        return false;
    }

    static void Main(string[] args)
    {
        // True
        Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
                                                  new List<string>()));
        // False
        Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
                                                  new string[0]));
        // True
        Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
                                                  new SubList()));
        // True
        Console.WriteLine(IsInstanceOfGenericType(typeof(List<>),
                                                  new SubList<int>()));
    }

    class SubList : List<string>
    {
    }

    class SubList<T> : List<T>
    {
    }
}

EDIT: As noted in comments, this may work for interfaces:

foreach (var i in type.GetInterfaces())
{
    if (i.IsGenericType && i.GetGenericTypeDefinition() == genericType)
    {
        return true;
    }
}

I have a sneaking suspicion there may be some awkward edge cases around this, but I can't find one it fails for right now.

82
ответ дан 24 November 2019 в 00:44
поделиться
return list.GetType().IsGenericType;
0
ответ дан 24 November 2019 в 00:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: