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

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


GenericParameterAttributes Перечисление

Определение

Описывает ограничения для параметра универсального типа универсального типа универсального типа или метода.

Это перечисление поддерживает побитовую комбинацию значений его членов.

C#
[System.Flags]
public enum GenericParameterAttributes
Наследование
GenericParameterAttributes
Атрибуты

Поля

Имя Значение Описание
AllowByRefLike 32

Параметр универсального типа может быть ByRefLike.

Contravariant 2

Параметр универсального типа является контравариантным. Параметр контравариантного типа может отображаться как тип параметра в сигнатурах метода.

Covariant 1

Параметр универсального типа является ковариантным. Параметр ковариантного типа может отображаться в качестве типа результата метода, типа поля только для чтения, объявленного базового типа или реализованного интерфейса.

DefaultConstructorConstraint 16

Тип можно заменить параметром универсального типа, только если он имеет конструктор без параметров.

None 0

Нет специальных флагов.

NotNullableValueTypeConstraint 8

Тип можно заменить параметром универсального типа только в том случае, если он является типом значения и не имеет значения NULL.

ReferenceTypeConstraint 4

Тип можно заменить параметром универсального типа, только если он является ссылочным типом.

SpecialConstraintMask 28

Выбирает сочетание всех флагов специальных ограничений. Это значение является результатом использования логических ИЛИ для объединения следующих флагов: DefaultConstructorConstraint, ReferenceTypeConstraintи NotNullableValueTypeConstraint.

VarianceMask 3

Выбирает сочетание всех флагов дисперсии. Это значение является результатом использования логических ИЛИ для объединения следующих флагов: Contravariant и Covariant.

Примеры

В следующем примере кода определяется универсальный тип Test с двумя параметрами типа. Второй параметр типа имеет ограничение базового класса и ограничение ссылочного типа. При выполнении программы ограничения проверяются с помощью свойства Type.GenericParameterAttributes и метода Type.GetGenericParameterConstraints.

C#
using System;
using System.Reflection;

// Define a sample interface to use as an interface constraint.
public interface ITest {}

// Define a base type to use as a base class constraint.
public class Base {}

// Define the generic type to examine. The first generic type parameter,
// T, derives from the class Base and implements ITest. This demonstrates
// a base class constraint and an interface constraint. The second generic 
// type parameter, U, must be a reference type (class) and must have a 
// default constructor (new()). This demonstrates special constraints.
//
public class Test<T,U> 
    where T : Base, ITest 
    where U : class, new() {}

// Define a type that derives from Base and implements ITest. This type
// satisfies the constraints on T in class Test.
public class Derived : Base, ITest {}

public class Example
{
    public static void Main()
    {
        // To get the generic type definition, omit the type
        // arguments but retain the comma to indicate the number
        // of type arguments. 
        //
        Type def = typeof(Test<,>);
        Console.WriteLine("\r\nExamining generic type {0}", def);

        // Get the type parameters of the generic type definition,
        // and display them.
        //
        Type[] defparams = def.GetGenericArguments();
        foreach (Type tp in defparams)
        {
            Console.WriteLine("\r\nType parameter: {0}", tp.Name);
            Console.WriteLine("\t{0}", 
                ListGenericParameterAttributes(tp));

            // List the base class and interface constraints. The
            // constraints are returned in no particular order. If 
            // there are no class or interface constraints, an empty
            // array is returned.
            //
            Type[] tpConstraints = tp.GetGenericParameterConstraints();
            foreach (Type tpc in tpConstraints)
            {
                Console.WriteLine("\t{0}", tpc);
            }
        }
    }

    // List the variance and special constraint flags. 
    //
    private static string ListGenericParameterAttributes(Type t)
    {
        string retval;
        GenericParameterAttributes gpa = t.GenericParameterAttributes;
        GenericParameterAttributes variance = gpa & 
            GenericParameterAttributes.VarianceMask;

        // Select the variance flags.
        if (variance == GenericParameterAttributes.None)
        {
            retval = "No variance flag;";
        }
        else
        {
            if ((variance & GenericParameterAttributes.Covariant) != 0)
                retval = "Covariant;";
            else
                retval = "Contravariant;";
        }

        // Select 
        GenericParameterAttributes constraints = gpa & 
            GenericParameterAttributes.SpecialConstraintMask;

        if (constraints == GenericParameterAttributes.None)
        {
            retval += " No special constraints";
        }
        else
        {
            if ((constraints & GenericParameterAttributes.ReferenceTypeConstraint) != 0)
                retval += " ReferenceTypeConstraint";
            if ((constraints & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
                retval += " NotNullableValueTypeConstraint";
            if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0)
                retval += " DefaultConstructorConstraint";
        }

        return retval;
    }
}
/* This example produces the following output:

Examining generic type Test`2[T,U]

Type parameter: T
        No variance flag; no special constraints.
        Base
        ITest

Type parameter: U
        No variance flag; ReferenceTypeConstraint DefaultConstructorConstraint
 */

Комментарии

Члены перечисления GenericParameterAttributes делятся на две группы, группу дисперсий и специальную группу ограничений. Чтобы проверить значение GenericParameterAttributes для флагов дисперсии, сначала выполните побитовую операцию AND с помощью VarianceMask. Если результат имеет значение None, флаги дисперсии отсутствуют. Аналогичным образом используйте SpecialConstraintMask для проверки флагов ограничений.

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

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.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, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0