영어로 읽기

다음을 통해 공유


GenericParameterAttributes 열거형

정의

제네릭 형식 또는 메서드의 제네릭 형식 매개 변수에 대한 제약 조건에 대해 설명합니다.

이 열거형은 멤버 값의 비트 조합을 지원합니다.

C#
[System.Flags]
public enum GenericParameterAttributes
상속
GenericParameterAttributes
특성

필드

Name Description
AllowByRefLike 32

제네릭 형식 매개 변수는 ByRefLike수 있습니다.

Contravariant 2

제네릭 형식 매개 변수는 반공변성입니다. 반공변 형식 매개 변수는 메서드 서명에서 매개 변수 형식으로 나타날 수 있습니다.

Covariant 1

제네릭 형식 매개 변수는 공변성입니다. 공변 형식 매개 변수는 메서드의 결과 형식, 읽기 전용 필드의 형식, 선언된 기본 형식 또는 구현된 인터페이스로 나타날 수 있습니다.

DefaultConstructorConstraint 16

매개 변수가 없는 생성자가 있는 경우에만 제네릭 형식 매개 변수로 형식을 대체할 수 있습니다.

None 0

특별한 플래그는 없습니다.

NotNullableValueTypeConstraint 8

제네릭 형식 매개 변수가 값 형식이고 null을 허용하지 않는 경우에만 형식을 제네릭 형식 매개 변수로 대체할 수 있습니다.

ReferenceTypeConstraint 4

제네릭 형식 매개 변수가 참조 형식인 경우에만 형식을 대체할 수 있습니다.

SpecialConstraintMask 28

모든 특수 제약 조건 플래그의 조합을 선택합니다. 이 값은 논리 OR을 사용하여 DefaultConstructorConstraint, ReferenceTypeConstraintNotNullableValueTypeConstraint플래그를 결합한 결과입니다.

VarianceMask 3

모든 분산 플래그의 조합을 선택합니다. 이 값은 논리 OR을 사용하여 ContravariantCovariant플래그를 결합한 결과입니다.

예제

다음 코드 예제에서는 두 개의 형식 매개 변수를 사용하여 제네릭 형식 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 값을 테스트하려면 먼저 VarianceMask를 사용하여 비트 AND 연산을 수행합니다. 결과가 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