Type.MakeGenericType メソッドとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > Type.MakeGenericType メソッドの意味・解説 

Type.MakeGenericType メソッド

メモ : このメソッドは、.NET Framework version 2.0新しく追加されたものです。

型の配列要素現在のジェネリック型定義型パラメータ置き換え結果構築型を表す Type オブジェクト返します

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Overridable Function
 MakeGenericType ( _
    ParamArray typeArguments As Type() _
) As Type
Dim instance As Type
Dim typeArguments As Type()
Dim returnValue As Type

returnValue = instance.MakeGenericType(typeArguments)
public virtual Type MakeGenericType (
    params Type[] typeArguments
)
public:
virtual Type^ MakeGenericType (
    ... array<Type^>^ typeArguments
)
public Type MakeGenericType (
    Type[] typeArguments
)
public function MakeGenericType (
    ... typeArguments : Type[]
) : Type

パラメータ

typeArguments

現在のジェネリック型型パラメータ置き換えられる型の配列

戻り値
typeArguments要素現在のジェネリック型型パラメータ置き換えることによって作られる構築型を表す Type

例外例外
例外種類条件

InvalidOperationException

現在の型はジェネリック型定義表しません。つまり、IsGenericTypeDefinition は false返します

ArgumentNullException

typeArgumentsnull 参照 (Visual Basic では Nothing) です。

または

typeArguments要素null 参照 (Visual Basic では Nothing) です。

ArgumentException

typeArguments要素の数が現在のジェネリック型定義型パラメータの数と同じではありません。

または

typeArguments要素現在のジェネリック型対応する型パラメータに対して指定され制約満たしていません。

解説解説

MakeGenericType メソッドにより、ジェネリック型定義型パラメータ固有の型を割り当てるコード記述して特定の構築型を表す Type オブジェクト作成できます。この Type オブジェクト使用して構築型の実行時インスタンス作成できます

MakeGenericType によって構築した型は開いた型にすることができます。つまり、これらの型の型引数いくつかは、包含するジェネリック メソッドまたはジェネリック型型パラメータにすることができます動的なアセンブリ出力する場合に、このようなオープン構築型を使用する場合あります。たとえば、次のコードBase クラスDerived クラスについて考えてましょう

Public Class Base(Of T,
 U)
End Class
Public Class Derived(Of
 V)
    Inherits Base(Of Integer,
 V)
End Class
public class Base<T, U> { }
public class Derived<V> : Base<int,
 V> { }

Derived動的アセンブリ生成するには、基本型構築する必要があります。そのためには、ジェネリック型引数 Int32 および型パラメータ VDerived から使用してクラス Base を表す TypeMakeGenericType メソッド呼び出します。型およびジェネリック型パラメータ両方とも Type オブジェクトによって表されるので、両方を含む配列MakeGenericType メソッドに渡すことができます

メモメモ

Base<int, V> などの構築型はコード出力時には有用ですが、MakeGenericType メソッドをこの型で呼び出すことはできません。ジェネリック型定義ではないからです。インスタンス化できるクローズ構築型を作成するには、最初に GetGenericTypeDefinition メソッド呼び出してジェネリック型定義を表す Type オブジェクト取得してから、目的型引数指定して MakeGenericType呼び出します。

MakeGenericType によって返される Type オブジェクトは、結果構築型の GetType メソッド、または同じ型引数使って同じジェネリック型定義から作成され任意の構築型の GetType メソッド呼び出して取得されType と同じです。

メモメモ

ジェネリック型配列そのものジェネリック型ではありません。したがってC<T>[] (Visual Basic の場合Dim ac() As C(Of T)) のような配列型MakeGenericType呼び出すことはできません。C<T>[] からクローズ ジェネリック型構築するには、GetElementType を呼び出してジェネリック型定義 C<T>取得しジェネリック型定義MakeGenericType呼び出して構築型を作成し最後に構築型で MakeArrayType メソッド呼び出して配列型作成しますポインタ型および ref 型 (Visual Basic では ByRef) でも同様です

ジェネリック リフレクション使用される用語の一定の条件一覧については、IsGenericType のプロパティ解説参照してください

入れ子にされた型

ジェネリック型C#C++、または Visual Basic使用して定義されている場合入れ子にされた型はすべてジェネリックです。入れ子にされた型がその型自体型パラメータ持ってない場合でも同様です。これら 3 種類の言語にはいずれも入れ子にされた型型パラメータ リスト包含する型の型パラメータ含まれいるからです。次のクラスについて考えてましょう

Public Class Outermost(Of
 T)
    Public Class Inner(Of
 U)
        Public Class Innermost1(Of
 V)
        End Class
        Public Class Innermost2
        End Class
    End Class
End Class
public class Outermost<T>
{
    public class Inner<U>
    {
        public class Innermost1<V> {}
        public class Innermost2 {}
    }
}
generic<typename T> public ref class
 Outermost
{
public:
    generic<typename U> ref class Inner
    {
    public:
        generic<typename V> ref class Innermost1 {};
        ref class Innermost2 {};
    };
};

入れ子になったクラス Inner型パラメータ リストには 2 つの型パラメータ (TU) が含まれています。最初型パラメータは、外側クラス型パラメータです。同様に入れ子になったクラス Innermost1型パラメータ リストには 3 つの型パラメータ (TU、および V) が含まれています。TU は、外側クラス型パラメータです。入れ子になったクラス Innermost2 には 2 つの型パラメータ (TU) が含まれています。これらは外側クラス型パラメータです。

包含する型のパラメータ リスト複数型パラメータ含まれている場合入れ子にされた型型パラメータ リストにはすべての型パラメータ順番含まれます。

入れ子にされた型ジェネリック型定義からジェネリック型構築するには、すべての包含する型の型引数配列連結して作られ配列指定して MakeGenericType メソッド呼び出します。この配列は一番外側がジェネリック型始まり入れ子にされた型型引数配列終了します (固有の型パラメータ持っている場合)。Innermost1インスタンス作成するには、T、U、および V に割り当てられる 3 つの型を含む配列指定して MakeGenericType メソッド呼び出します。Innermost2インスタンス作成するには、T および U に割り当てられる 2 つの型を含む配列指定して MakeGenericType メソッド呼び出します。

このようにして各言語包含する型の型パラメータ反映されるので、包含する型の型パラメータ使用して入れ子にされた型フィールドを定義できますそうでない場合は、型パラメータ入れ子にされた型本体内のスコープ入りません。動的なアセンブリコード出力するか、または MSIL アセンブラ (Ilasm.exe) を使用すると、包含する型の型パラメータ反映せずに、入れ子にされた型定義することもできます次の MSIL アセンブラコードについて考えてます。

この例では、Innermost クラスの型 T または Uフィールドを定義できません。これらの型パラメータスコープ外だからです。次のアセンブラ コードは、C++Visual Basic、および C#定義され場合同じよう動作する入れ子になったクラス定義してます。

.class public Outer<T> {
    .class nested public Inner<T, U> {
        .class nested public Innermost<T, U, V> {
        }
    }
}

MSIL 逆アセンブラ (Ildasm.exe) を使用して高レベル言語定義されている入れ子になったクラス調べて、名前付けスキーム確認することができます

使用例使用例

MakeGenericType メソッド使用してDictionary 型のジェネリック型定義から構築型を作成する例を次に示します構築型は、文字列キーTest オブジェクト Dictionary表します

Imports System
Imports System.Reflection
Imports System.Collections.Generic
Imports Microsoft.VisualBasic

Public Class Test
    Public Shared Sub Main()
        Console.WriteLine(vbCrLf & "--- Create a constructed
 type from the generic Dictionary type.")

        ' Create a type object representing the generic Dictionary 
        ' type, by omitting the type arguments (but keeping the 
        ' comma that separates them, so the compiler can infer the
        ' number of type parameters).
        Dim generic As Type = GetType(Dictionary(Of
 ,))
        DisplayTypeInfo(generic)

        ' Create an array of types to substitute for the type
        ' parameters of Dictionary. The key is of type string, and
        ' the type to be contained in the Dictionary is Test.
        Dim typeArgs() As Type = { GetType(String),
 GetType(Test) }

        ' Create a Type object representing the constructed generic
        ' type.
        Dim constructed As Type = generic.MakeGenericType(typeArgs)
        DisplayTypeInfo(constructed)

        ' Compare the type objects obtained above to type objects
        ' obtained using GetType() and GetGenericTypeDefinition().
        Console.WriteLine(vbCrLf & "--- Compare types obtained
 by different methods:")

        Dim t As Type = GetType(Dictionary(Of
 String, Test))
        Console.WriteLine(vbTab & "Are the constructed types
 equal? " _
            & (t Is constructed))
        Console.WriteLine(vbTab & "Are the generic types equal?
 " _ 
            & (t.GetGenericTypeDefinition() Is generic))
    End Sub

    Private Shared Sub DisplayTypeInfo(ByVal
 t As Type)
        Console.WriteLine(vbCrLf & t.ToString())

        Console.WriteLine(vbTab & "Is this a generic type
 definition? " _ 
            & t.IsGenericTypeDefinition)

        Console.WriteLine(vbTab & "Is it a generic type? "
 _ 
            & t.IsGenericType)

        Dim typeArguments() As Type = t.GetGenericArguments()
        Console.WriteLine(vbTab & "List type arguments ({0}):",
 _
            typeArguments.Length)
        For Each tParam As
 Type In typeArguments       
            Console.WriteLine(vbTab & vbTab & tParam.ToString())
        Next
    End Sub
End Class

' This example produces the following output:
'
'--- Create a constructed type from the generic Dictionary type.
'
'System.Collections.Generic.Dictionary'2[TKey,TValue]
'        Is this a generic type definition? True
'        Is it a generic type? True
'        List type arguments (2):
'                TKey
'                TValue
'
'System.Collections.Generic.Dictionary`2[System.String,Test]
'        Is this a generic type definition? False
'        Is it a generic type? True
'        List type arguments (2):
'                System.String
'                Test
'
'--- Compare types obtained by different methods:
'        Are the constructed types equal? True
'        Are the generic types equal? True
using System;
using System.Reflection;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        Console.WriteLine("\r\n--- Create a constructed type from the generic
 Dictionary type.");

        // Create a type object representing the generic Dictionary
 
        // type, by omitting the type arguments (but keeping the 
        // comma that separates them, so the compiler can infer the
        // number of type parameters).      
        Type generic = typeof(Dictionary<,>);
        DisplayTypeInfo(generic);

        // Create an array of types to substitute for the type
        // parameters of Dictionary. The key is of type string, and
        // the type to be contained in the Dictionary is Test.
        Type[] typeArgs = { typeof(string), typeof(Test) };

        // Create a Type object representing the constructed generic
        // type.
        Type constructed = generic.MakeGenericType(typeArgs);
        DisplayTypeInfo(constructed);

        // Compare the type objects obtained above to type objects
        // obtained using typeof() and GetGenericTypeDefinition().
        Console.WriteLine("\r\n--- Compare types obtained by different methods:");

        Type t = typeof(Dictionary<String, Test>);
        Console.WriteLine("\tAre the constructed types equal? {0}", t ==
 constructed);
        Console.WriteLine("\tAre the generic types equal? {0}", 
            t.GetGenericTypeDefinition() == generic);
    }

    private static void
 DisplayTypeInfo(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);

        Type[] typeArguments = t.GetGenericArguments();
        Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
        foreach (Type tParam in typeArguments)
        {
            Console.WriteLine("\t\t{0}", tParam);
        }
    }
}

/* This example produces the following output:

--- Create a constructed type from the generic Dictionary type.

System.Collections.Generic.Dictionary`2[TKey,TValue]
        Is this a generic type definition? True
        Is it a generic type? True
        List type arguments (2):
                TKey
                TValue

System.Collections.Generic.Dictionary`2[System.String, Test]
        Is this a generic type definition? False
        Is it a generic type? True
        List type arguments (2):
                System.String
                Test

--- Compare types obtained by different methods:
        Are the constructed types equal? True
        Are the generic types equal? True
 */
using namespace System;
using namespace System::Reflection;
using namespace System::Collections::Generic;

namespace Example
{
    public ref class Test
    {
    public:
        static void CreateConstructedType(void)
        {      
            Console::WriteLine("\r\n--- Create a constructed type"
                " from the generic Dictionary`2 type.");
            
            // Create a type object representing 
            // the generic Dictionary`2 type.
            Type^ genericType = Type::GetType(
                "System.Collections.Generic.Dictionary`2");
            if (genericType != nullptr)
            {  
                DisplayTypeInfo(genericType);
            }
            else
            {
                Console::WriteLine("The type is not found");
                return;
            }
            
            // Create an array of types to substitute for the type
            // parameters of Dictionary`2. 
            // The key is of type string, and the type to be 
            // contained in the Dictionary`2 is Test.
            array<Type^>^ typeArgs = {String::typeid, Test::typeid};
            Type^ constructedType = 
                genericType->MakeGenericType(typeArgs);
            DisplayTypeInfo(constructedType);
            
            // Compare the type objects obtained above to type objects
            // obtained using typeof() and GetGenericTypeDefinition().
            Console::WriteLine("\r\n--- Compare types obtained by"
                " different methods:");

            Type^ definedType = Dictionary<String^, Test^>::typeid;
            Console::WriteLine("\tAre the constructed types "
                "equal? {0}", definedType == constructedType);
            Console::WriteLine("\tAre the generic types equal? {0}", 
                definedType->GetGenericTypeDefinition() == genericType);
        }

    private:
        static void DisplayTypeInfo(Type^ typeToDisplay)
        {   
            Console::WriteLine("\r\n{0}", typeToDisplay);
            Console::WriteLine("\tIs this a generic type
 definition? "
                "{0}", typeToDisplay->IsGenericTypeDefinition);
            Console::WriteLine("\tIs it a generic type? "
                "{0}", typeToDisplay->IsGenericType);
            
            array<Type^>^ typeArguments = 
                typeToDisplay->GetGenericArguments();
            Console::WriteLine("\tList type arguments ({0}):", 
                typeArguments->Length);
            
            for each (Type^ typeArgument in
 typeArguments)
            {   
                Console::WriteLine("\t\t{0}", typeArgument);
            }
        }
    };
}

int main(void)
{
    Example::Test::CreateConstructedType();
}

/* This example produces the following output:

--- Create a constructed type from the generic Dictionary`2 type.

System.Collections.Generic.Dictionary`2[KeyType,ValueType]
          Is this a generic type definition? True
          Is it a generic type? True
          List type arguments (2):
                     K
                     V

System.Collections.Generic.Dictionary`2[System.String, Test]
          Is this a generic type definition? False
          Is it a generic type? True
          List type arguments (2):
                     System.String
                     Test

--- Compare types obtained by different methods:
          Are the constructed types equal? True
          Are the generic types equal? True
 */
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照


このページでは「.NET Framework クラス ライブラリ リファレンス」からType.MakeGenericType メソッドを検索した結果を表示しています。
Weblioに収録されているすべての辞書からType.MakeGenericType メソッドを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からType.MakeGenericType メソッド を検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Type.MakeGenericType メソッド」の関連用語

Type.MakeGenericType メソッドのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Type.MakeGenericType メソッドのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS