GenericParameterAttributes GenericParameterAttributes GenericParameterAttributes GenericParameterAttributes Enum

定義

ジェネリック型またはメソッドのジェネリック型パラメーターの制約について記述します。Describes the constraints on a generic type parameter of a generic type or method.

この列挙型には FlagsAttribute 属性があり、メンバー値ではビットごとの組み合わせを使用できます。

public enum class GenericParameterAttributes
[System.Flags]
public enum GenericParameterAttributes
type GenericParameterAttributes = 
Public Enum GenericParameterAttributes
継承
GenericParameterAttributesGenericParameterAttributesGenericParameterAttributesGenericParameterAttributes
属性

フィールド

Contravariant Contravariant Contravariant Contravariant 2

ジェネリック型パラメーターが反変の型パラメーターです。The generic type parameter is contravariant. 反変の型パラメーターは、メソッドのシグネチャのパラメーター型として現れます。A contravariant type parameter can appear as a parameter type in method signatures.

Covariant Covariant Covariant Covariant 1

ジェネリック型パラメーターが共変の型パラメーターです。The generic type parameter is covariant. 共変の型パラメーターは、メソッドの結果型、読み取り専用フィールドの型、宣言された基本型、または実装されたインターフェイスとして現れます。A covariant type parameter can appear as the result type of a method, the type of a read-only field, a declared base type, or an implemented interface.

DefaultConstructorConstraint DefaultConstructorConstraint DefaultConstructorConstraint DefaultConstructorConstraint 16

型がパラメーターなしのコンストラクターを持つ場合のみ、その型をジェネリック型パラメーターの代わりに使用できます。A type can be substituted for the generic type parameter only if it has a parameterless constructor.

None None None None 0

特別なフラグはありません。There are no special flags.

NotNullableValueTypeConstraint NotNullableValueTypeConstraint NotNullableValueTypeConstraint NotNullableValueTypeConstraint 8

型が値型で null 許容でない場合のみ、その型をジェネリック型パラメーターの代わりに使用できます。A type can be substituted for the generic type parameter only if it is a value type and is not nullable.

ReferenceTypeConstraint ReferenceTypeConstraint ReferenceTypeConstraint ReferenceTypeConstraint 4

型が参照型である場合のみ、その型をジェネリック型パラメーターの代わりに使用できます。A type can be substituted for the generic type parameter only if it is a reference type.

SpecialConstraintMask SpecialConstraintMask SpecialConstraintMask SpecialConstraintMask 28

すべての特殊な制約フラグの組み合わせを選択します。Selects the combination of all special constraint flags. この値は、論理 OR を使用して DefaultConstructorConstraint フラグ、ReferenceTypeConstraint フラグ、および NotNullableValueTypeConstraint フラグを組み合わせた結果です。This value is the result of using logical OR to combine the following flags: DefaultConstructorConstraint, ReferenceTypeConstraint, and NotNullableValueTypeConstraint.

VarianceMask VarianceMask VarianceMask VarianceMask 3

すべての変性フラグの組み合わせを選択します。Selects the combination of all variance flags. この値は、論理 OR を使用して Contravariant フラグと Covariant フラグを組み合わせた結果です。This value is the result of using logical OR to combine the following flags: Contravariant and Covariant.

次のコード例は、ジェネリック型を定義します。 Test 2 つの型パラメーターを使用します。The following code example defines a generic type Test with two type parameters. 2 番目の型パラメーターには、基底クラスの制約と参照型の制約があります。The second type parameter has a base class constraint and a reference type constraint. 使用して、制約をチェックするプログラムを実行するとき、Type.GenericParameterAttributesプロパティおよびType.GetGenericParameterConstraintsメソッド。When the program executes, the constraints are examined using the Type.GenericParameterAttributes property and the Type.GetGenericParameterConstraints method.

using namespace System;
using namespace System::Collections;
using namespace System::Reflection;

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

// Define a base type to use as a class constraint.
public ref 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. In the .NET
// Framework version 2.0, C++ has no way of expressing special constraints.
// See the C# example code.
//
generic <typename T, typename U>
   where T :  Base, ITest
ref class Test {};

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

public ref class Example
{
public:
   static void Main()
   {
      // Create a constructed type from Test<T,U>, and from it
      // get the generic type definition.
      //
      Type^ def = Test::typeid;
      Console::WriteLine( L"\r\nExamining generic type {0}", def );
      
      // Get the type parameters of the generic type definition,
      // and display them.
      //
      for each (Type^ tp in def->GetGenericArguments())
      {
         Console::WriteLine( L"\r\nType parameter: {0}", tp);
         Console::WriteLine( L"\t{0}", 
            ListGenericParameterAttributes( tp ) );
         
         // List the base class and interface constraints. The
         // constraints do not appear in any particular order. If
         // there are no class or interface constraints, an empty
         // array is returned.
         //
         for each (Type^ constraint in tp->GetGenericParameterConstraints())
         {
            Console::WriteLine( L"\t{0}", constraint );
         }
      }
   }

private:

   // List the variance and special constraint flags. 
   //
   static String^ ListGenericParameterAttributes( Type^ t )
   {
      String^ retval;
      GenericParameterAttributes gpa = t->GenericParameterAttributes;

      // Select the variance flag.
      GenericParameterAttributes variance =
         static_cast<GenericParameterAttributes>(
            gpa & GenericParameterAttributes::VarianceMask );

      if ( variance == GenericParameterAttributes::None )
            retval = L"No variance flag;";
      else
      {
         if ( (variance & GenericParameterAttributes::Covariant) !=
               GenericParameterAttributes::None )
            retval = L"Covariant;";
         else
            retval = L"Contravariant;";
      }

      // Select the special constraint flags.
      GenericParameterAttributes constraints =
         static_cast<GenericParameterAttributes>(
            gpa & GenericParameterAttributes::SpecialConstraintMask);

      if ( constraints == GenericParameterAttributes::None )
            retval = String::Concat( retval, L" No special constraints" );
      else
      {
         if ( (constraints & GenericParameterAttributes::ReferenceTypeConstraint) !=
               GenericParameterAttributes::None )
            retval = String::Concat( retval, L" ReferenceTypeConstraint" );

         if ( (constraints & GenericParameterAttributes::NotNullableValueTypeConstraint) !=
               GenericParameterAttributes::None )
            retval = String::Concat( retval, L" NotNullableValueTypeConstraint" );

         if ( (constraints & GenericParameterAttributes::DefaultConstructorConstraint) !=
               GenericParameterAttributes::None )
            retval = String::Concat( retval, L" DefaultConstructorConstraint" );
      }

      return retval;
   }
};

int main()
{
   Example::Main();
}

/* 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; No special constraints
 */
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
 */
Imports System
Imports System.Reflection

' Define a sample interface to use as an interface constraint.
Public Interface ITest
End Interface 

' Define a base type to use as a base class constraint.
Public Class Base
End Class 

' 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(Of T As {Base, ITest}, U As {New, Class}) 
End Class

' Define a type that derives from Base and implements ITtest. This type
' satisfies the constraints on T in class Test.
Public Class Derived
    Inherits Base
    Implements ITest
End Class 

Public Class Example
    
    Public Shared Sub Main() 
        ' To get the generic type definition, omit the type
        ' arguments but retain the comma to indicate the number
        ' of type arguments. 
        '
        Dim def As Type = GetType(Test(Of ,))
        Console.WriteLine(vbCrLf & "Examining generic type {0}", def)
        
        ' Get the type parameters of the generic type definition,
        ' and display them.
        '
        Dim defparams() As Type = def.GetGenericArguments()
        For Each tp As Type In defparams

            Console.WriteLine(vbCrLf & "Type parameter: {0}", tp.Name)
            Console.WriteLine(vbTab & ListGenericParameterAttributes(tp))
            
            ' List the base class and interface constraints. The
            ' constraints do not appear in any particular order. An
            ' empty array is returned if there are no constraints.
            '
            Dim tpConstraints As Type() = _
                tp.GetGenericParameterConstraints()
            For Each tpc As Type In  tpConstraints
                Console.WriteLine(vbTab & tpc.ToString())
            Next tpc
        Next tp
    
    End Sub 
    
    ' List the variance and special constraint flags.
    '
    Private Shared Function ListGenericParameterAttributes(ByVal t As Type) As String 
        Dim retval As String
        Dim gpa As GenericParameterAttributes = t.GenericParameterAttributes

        ' Select the variance flags.
        Dim variance As GenericParameterAttributes = _
            gpa And GenericParameterAttributes.VarianceMask
        
        If variance = GenericParameterAttributes.None Then
            retval = "No variance flag;"
        Else
            If (variance And GenericParameterAttributes.Covariant) <> 0 Then
                retval = "Covariant;"
            Else
                retval = "Contravariant;"
            End If
        End If 

        ' Select the constraint flags.
        Dim constraints As GenericParameterAttributes = _
            gpa And GenericParameterAttributes.SpecialConstraintMask
        
        If constraints = GenericParameterAttributes.None Then
            retval &= " no special constraints."
        Else
            If (constraints And GenericParameterAttributes.ReferenceTypeConstraint) <> 0 Then
                retval &= " ReferenceTypeConstraint"
            End If
            If (constraints And GenericParameterAttributes.NotNullableValueTypeConstraint) <> 0 Then
                retval &= " NotNullableValueTypeConstraint"
            End If
            If (constraints And GenericParameterAttributes.DefaultConstructorConstraint) <> 0 Then
                retval &= " DefaultConstructorConstraint"
            End If
        End If 
        Return retval
    
    End Function 
End Class 
' 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列挙体は 2 つのグループ、差異グループ、および特殊な制約のグループに分けられます。The members of the GenericParameterAttributes enumeration are divided into two groups, the variance group and the special constraints group. テストする、GenericParameterAttributes変性フラグの値で、まず VarianceMask でビットごとの AND 演算を実行します。To test a GenericParameterAttributes value for variance flags, first perform a bitwise AND operation with VarianceMask. 結果が None の場合は、変性フラグはありません。If the result is None, there are no variance flags. 同様に、制約のフラグをテストする SpecialConstraintMask を使用します。Similarly, use SpecialConstraintMask to test for constraint flags.

適用対象