Прочитать на английском

Поделиться через


Type.ContainsGenericParameters Свойство

Определение

Возвращает значение, позволяющее определить, имеются ли у текущего объекта Type параметры типа, которые не были замещены указанными типами.

public virtual bool ContainsGenericParameters { get; }

Значение свойства

Boolean

Значение true, если объект Type сам является параметром универсального типа или если для его параметров типа не предоставлены определенные типы; в противном случае — значение false.

Примеры

В следующем примере определяется универсальный класс с двумя параметрами типа, а затем определяется второй универсальный класс, производный от первого класса. Базовый класс производного класса имеет два аргумента типа: первый — Int32 , а второй — параметр типа производного типа. В примере отображаются сведения об этих универсальных классах, включая позиции, сообщаемые GenericParameterPosition свойством.

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

// Define a base class with two type parameters.
public class Base<T, U> { }

// Define a derived class. The derived class inherits from a constructed
// class that meets the following criteria:
//   (1) Its generic type definition is Base<T, U>.
//   (2) It specifies int for the first type parameter.
//   (3) For the second type parameter, it uses the same type that is used
//       for the type parameter of the derived class.
// Thus, the derived class is a generic type with one type parameter, but
// its base class is an open constructed type with one type argument and
// one type parameter.
public class Derived<V> : Base<int, V> { }

public class Test
{
    public static void Main()
    {
        Console.WriteLine(
            "\r\n--- Display a generic type and the open constructed");
        Console.WriteLine("    type from which it is derived.");

        // Create a Type object representing the generic type definition 
        // for the Derived type, by omitting the type argument. (For
        // types with multiple type parameters, supply the commas but
        // omit the type arguments.) 
        //
        Type derivedType = typeof(Derived<>);
        DisplayGenericTypeInfo(derivedType);

        // Display its open constructed base type.
        DisplayGenericTypeInfo(derivedType.BaseType);
    }

    private static void DisplayGenericTypeInfo(Type t)
    {
        Console.WriteLine("\r\n{0}", t);

        Console.WriteLine("\tIs this a generic type definition? {0}", 
            t.IsGenericTypeDefinition);

        Console.WriteLine("\tIs it a generic type? {0}", 
            t.IsGenericType);

        Console.WriteLine("\tDoes it have unassigned generic parameters? {0}", 
            t.ContainsGenericParameters);

        if (t.IsGenericType)
        {
            // If this is a generic type, display the type arguments.
            //
            Type[] typeArguments = t.GetGenericArguments();

            Console.WriteLine("\tList type arguments ({0}):", 
                typeArguments.Length);

            foreach (Type tParam in typeArguments)
            {
                // IsGenericParameter is true only for generic type
                // parameters.
                //
                if (tParam.IsGenericParameter)
                {
                    Console.WriteLine(
                        "\t\t{0}  (unassigned - parameter position {1})",
                        tParam,
                        tParam.GenericParameterPosition);
                }
                else
                {
                    Console.WriteLine("\t\t{0}", tParam);
                }
            }
        }
    }
}

/* This example produces the following output:

--- Display a generic type and the open constructed
    type from which it is derived.

Derived`1[V]
        Is this a generic type definition? True
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (1):
                V  (unassigned - parameter position 0)

Base`2[System.Int32,V]
        Is this a generic type definition? False
        Is it a generic type? True
        Does it have unassigned generic parameters? True
        List type arguments (2):
                System.Int32
                V  (unassigned - parameter position 0)
 */

Комментарии

Чтобы создать экземпляр типа, не должно быть определений универсального типа или открытых сконструированных типов в аргументах типа самого типа, во всех включающих универсальных типах или в любых элементах типа. Другой способ сказать, что при рекурсивном исследовании тип не должен содержать параметров универсального типа.

Так как типы могут быть произвольными сложными, такое определение сложно. Для удобства и снижения вероятности возникновения ошибки ContainsGenericParameters свойство предоставляет стандартный способ различения закрытых сконструированных типов, для которых можно создать экземпляры, и открытых сконструированных типов, которые не могут. Если ContainsGenericParameters свойство возвращает true , экземпляр типа не может быть создан.

ContainsGenericParametersСвойство выполняет поиск параметров типа рекурсивно. например, он возвращает true для массива, элементы которого имеют тип A<T> ( A(Of T) в Visual Basic), несмотря на то, что массив не является универсальным. Сравните это с поведением IsGenericType свойства, которое возвращает false для массивов.

Набор примеров классов и таблица, в которой показаны значения ContainsGenericParameters свойства, см. в разделе IsGenericType .

Применяется к

Продукт Версии
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

См. также раздел