Ler em inglês

Compartilhar via


GenericParameterAttributes Enumeração

Definição

Descreve as restrições em um parâmetro de tipo genérico de um tipo ou método genérico.

Essa enumeração dá suporte a uma combinação bit a bit dos valores de membro.

C#
[System.Flags]
public enum GenericParameterAttributes
Herança
GenericParameterAttributes
Atributos

Campos

Nome Valor Description
AllowByRefLike 32

O parâmetro de tipo genérico pode ser ByRefLike.

Contravariant 2

O parâmetro de tipo genérico é contravariante. Um parâmetro de tipo contravariante pode aparecer como um tipo de parâmetro em assinaturas de método.

Covariant 1

O parâmetro de tipo genérico é covariante. Um parâmetro de tipo covariante pode aparecer como o tipo de resultado de um método, o tipo de um campo somente leitura, um tipo de base declarado ou uma interface implementada.

DefaultConstructorConstraint 16

Um tipo só poderá ser substituído pelo parâmetro de tipo genérico se ele tiver um construtor sem parâmetros.

None 0

Não há sinalizadores especiais.

NotNullableValueTypeConstraint 8

Um tipo pode ser substituído pelo parâmetro de tipo genérico somente se for um tipo de valor e não for anulável.

ReferenceTypeConstraint 4

Um tipo só poderá ser substituído pelo parâmetro de tipo genérico se for um tipo de referência.

SpecialConstraintMask 28

Seleciona a combinação de todos os sinalizadores de restrição especiais. Esse valor é o resultado do uso de OR lógico para combinar os seguintes sinalizadores: DefaultConstructorConstraint, ReferenceTypeConstrainte NotNullableValueTypeConstraint.

VarianceMask 3

Seleciona a combinação de todos os sinalizadores de variação. Esse valor é o resultado do uso de OR lógico para combinar os seguintes sinalizadores: Contravariant e Covariant.

Exemplos

O exemplo de código a seguir define um tipo genérico Test com dois parâmetros de tipo. O segundo parâmetro de tipo tem uma restrição de classe base e uma restrição de tipo de referência. Quando o programa é executado, as restrições são examinadas usando a propriedade Type.GenericParameterAttributes e o método 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
 */

Comentários

Os membros da enumeração GenericParameterAttributes são divididos em dois grupos, o grupo de variação e o grupo de restrições especiais. Para testar um valor GenericParameterAttributes para sinalizadores de variação, primeiro execute uma operação AND bit a bit com VarianceMask. Se o resultado for Nenhum, não haverá sinalizadores de variação. Da mesma forma, use SpecialConstraintMask para testar sinalizadores de restrição.

Aplica-se a

Produto Versões
.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