Type.MakeGenericType(Type[]) Yöntem
Tanım
Önemli
Bazı bilgiler ürünün ön sürümüyle ilgilidir ve sürüm öncesinde önemli değişiklikler yapılmış olabilir. Burada verilen bilgilerle ilgili olarak Microsoft açık veya zımni hiçbir garanti vermez.
Geçerli genel tür tanımının tür parametreleri için bir tür dizisinin öğelerinin yerini alır ve sonuçta elde edilen türü temsil eden bir Type nesne döndürür.
public:
abstract Type ^ MakeGenericType(... cli::array <Type ^> ^ typeArguments);
public:
virtual Type ^ MakeGenericType(... cli::array <Type ^> ^ typeArguments);
public abstract Type MakeGenericType(params Type[] typeArguments);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")]
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
public virtual Type MakeGenericType(params Type[] typeArguments);
public virtual Type MakeGenericType(params Type[] typeArguments);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
public virtual Type MakeGenericType(params Type[] typeArguments);
abstract member MakeGenericType : Type[] -> Type
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")>]
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")>]
abstract member MakeGenericType : Type[] -> Type
override this.MakeGenericType : Type[] -> Type
abstract member MakeGenericType : Type[] -> Type
override this.MakeGenericType : Type[] -> Type
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")>]
abstract member MakeGenericType : Type[] -> Type
override this.MakeGenericType : Type[] -> Type
Public MustOverride Function MakeGenericType (ParamArray typeArguments As Type()) As Type
Public Overridable Function MakeGenericType (ParamArray typeArguments As Type()) As Type
Parametreler
- typeArguments
- Type[]
Geçerli genel türün tür parametreleriyle değiştirilecek bir tür dizisi.
Döndürülenler
Type Geçerli genel türün tür parametreleri için öğelerinin typeArguments yerini alarak oluşturulan türü temsil eden.
- Öznitelikler
Özel durumlar
Geçerli tür genel tür tanımını temsil etmiyor. Yani döndürür IsGenericTypeDefinitionfalse.
typeArguments, null'e eşittir.
-veya-
öğesinin typeArguments herhangi bir öğesidir null.
içindeki typeArguments öğe sayısı, geçerli genel tür tanımındaki tür parametrelerinin sayısıyla aynı değildir.
-veya-
typeArguments öğesi, geçerli genel türün karşılık gelen tür parametresi için belirtilen kısıtlamaları karşılamaz.
-veya-
typeArguments , işaretçi türü (IsPointer döndürür true), başv türü (IsByRef döndürür true) veya Voidolan bir öğe içerir.
Çağrılan yöntem temel sınıfta desteklenmez. Türetilmiş sınıfların bir uygulama sağlaması gerekir.
Örnekler
Aşağıdaki örnek, türü için MakeGenericType genel tür tanımından bir tür oluşturmak için Dictionary<TKey,TValue> yöntemini kullanır. Yapı türü, dize anahtarları olan nesnelerin bir Dictionary<TKey,TValue> öğesini Test temsil eder.
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
*/
open System
open System.Collections.Generic
type Test() = class end
let displayTypeInfo (t: Type) =
printfn $"\r\n{t}"
printfn $"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"
printfn $"\tIs it a generic type? {t.IsGenericType}"
let typeArguments = t.GetGenericArguments()
printfn $"\tList type arguments ({typeArguments.Length}):"
for tParam in typeArguments do
printfn $"\t\t{tParam}"
printfn "\r\n--- Create a constructed type from the generic Dictionary type."
// Create a type object representing the generic Dictionary
// type, by calling .GetGenericTypeDefinition().
let generic = typeof<Dictionary<_,_>>.GetGenericTypeDefinition()
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.
let typeArgs = [| typeof<string>; typeof<Test> |]
// Create a Type object representing the constructed generic type.
let constructed = generic.MakeGenericType typeArgs
displayTypeInfo constructed
(* 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
*)
Public Class Test
Public Shared Sub Main2()
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
Açıklamalar
yöntemi, MakeGenericType genel tür tanımının tür parametrelerine belirli türler atayan kod yazmanıza olanak tanır, böylece belirli bir yapı türünü temsil eden bir Type nesne oluşturur. Bu Type nesneyi, oluşturduğunuz türün çalışma zamanı örneklerini oluşturmak için kullanabilirsiniz.
MakeGenericType ile oluşturulan türler açık türler olabilir; başka bir ifadeyle, bağımsız tür argümanlarından bazıları, genel yöntemleri veya türleri kapsayanın tür parametreleri olabilir. Dinamik derlemeler yayarken bu tür açık oluşturulmuş türleri kullanabilirsiniz. Örneğin, aşağıdaki kodda Base ve Derived sınıflarını göz önünde bulundurun.
public class Base<T, U> { }
public class Derived<V> : Base<int, V> { }
type Base<'T, 'U>() = class end
type Derived<'V>() = inherit Base<int, 'V>()
Public Class Base(Of T, U)
End Class
Public Class Derived(Of V)
Inherits Base(Of Integer, V)
End Class
Dinamik bir derlemede Derived oluşturmak için, temel türünü inşa etmek gereklidir. Bunu yapmak için, MakeGenericType nesnesinde, sınıf Type'yi temsil eden, Base genel tür bağımsız değişkenlerini ve Int32'den V tür parametresini kullanarak Derived yöntemini çağırın. Türler ve genel tür parametreleri Type nesneler tarafından temsil edildiğinden, her ikisini içeren bir dizi MakeGenericType yöntemine geçirilebilir.
Note
Base<int, V> gibi oluşturulmuş bir tür, kod oluştururken yararlıdır, ancak bu tür bir genel tür tanımı olmadığından MakeGenericType yöntemini çağıramazsınız. Örneği oluşturulabilen kapalı bir yapılı tür oluşturmak için, önce GetGenericTypeDefinition yöntemini çağırarak genel tür tanımını temsil eden bir Type nesne alın ve daha sonra istenen tür bağımsız değişkenleriyle MakeGenericType'yi çağırın.
Type tarafından döndürülen MakeGenericType nesnesi, oluşturulan bir türün Type yöntemi veya aynı genel tür tanımından, aynı tür bağımsız değişkenleri kullanarak oluşturulan herhangi bir türün GetType yöntemi çağrılarak elde edilen GetType ile aynıdır.
Note
Genel türlerden oluşan bir dizi, genel bir tür değildir. ( Visual Basic'te) gibi MakeGenericTypeC<T>[] bir dizi türünde çağrı Dim ac() As C(Of T) yapamazsınız.
C<T>[]'den kapalı bir genel tür oluşturmak için, GetElementType'i çağırarak genel tür tanımını C<T>'den alın; oluşturulmuş türü yaratmak için genel tür tanımında MakeGenericType'ü çağırın ve son olarak dizi türünü oluşturmak için oluşturulan türdeki MakeArrayType yöntemini çağırın. İşaretçi türleri ve ref türleri için de aynı durum geçerlidir (ByRef Visual Basic'te).
Genel yansımada kullanılan terimlere ilişkin sabit koşulların IsGenericType listesi için özellik açıklamalarına bakın.
İç içe geçmiş türler
Genel bir tür C#, C++ veya Visual Basic kullanılarak tanımlanmışsa, iç içe türlerin tümü geneldir. İç içe türlerin kendi tür parametreleri olmasa bile bu durum geçerlidir, çünkü üç dil de iç içe türlerin tür parametre listelerinde kapsayan türlerin tür parametrelerini içerir. Aşağıdaki sınıfları göz önünde bulundurun:
public class Outermost<T>
{
public class Inner<U>
{
public class Innermost1<V> {}
public class Innermost2 {}
}
}
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
İç içe sınıfın Inner tür parametre listesinde iki tür parametresi T vardır ve Ubunlardan ilki, kapsayan sınıfının tür parametresidir. Benzer şekilde, iç içe sınıfın Innermost1 tür parametre listesi, T, U ve V olmak üzere üç tür parametresi barındırır; T ve U ise kapsayan sınıflardan gelmektedir. İç içe geçmiş sınıf Innermost2, kapsayan sınıflarından gelen T ve U olmak üzere iki tür parametresi vardır.
Kapsayan türün parametre listesinde birden fazla tür parametresi varsa, sırasıyla tüm tür parametreleri iç içe türün tür parametre listesine eklenir.
MakeGenericType yöntemini çağırmak için, iç içe bir türün genel tür tanımından genel bir tür oluştururken, en dıştaki genel türden başlayarak tüm kapsayan türlerin tür bağımsız değişken dizilerini birleştirin ve eğer kendi tür parametreleri varsa, iç içe türün tür bağımsız değişken dizisini ekleyin. örneğini Innermost1oluşturmak için T, U ve V'ye atanacak üç tür içeren bir dizi ile yöntemini çağırın MakeGenericType . örneğini Innermost2oluşturmak için, T ve U'ya atanacak iki tür içeren bir dizi ile yöntemini çağırın MakeGenericType .
Diller, iç içe türlerin alanlarını tanımlamak için bir kapsayan türün tür parametrelerini kullanabilmenizi sağlamak amacıyla, kapsayan türlerin tür parametrelerini bu şekilde yayar. Aksi takdirde, tür parametreleri iç içe türlerin gövdeleri içinde kapsamda bulunmaz. İç içe türleri, kapsayan türlerin tür parametrelerini yaymadan, kodu dinamik derlemelerde ya da Ilasm.exe (IL Assembler) kullanarak tanımlamak mümkündür. CIL derleyicisi için aşağıdaki kodu göz önünde bulundurun:
.class public Outer<T> {
.class nested public Inner<U> {
.class nested public Innermost {
}
}
}
Bu örnekte, türünde T veya U sınıfında Innermostbir alan tanımlamak mümkün değildir çünkü bu tür parametreleri kapsam içinde değildir. Aşağıdaki derleyici kodu C++, Visual Basic ve C# içinde tanımlandığında olduğu gibi davranan iç içe sınıfları tanımlar:
.class public Outer<T> {
.class nested public Inner<T, U> {
.class nested public Innermost<T, U, V> {
}
}
}
üst düzey dillerde tanımlanan iç içe sınıfları incelemek ve bu adlandırma düzenini gözlemlemek için Ildasm.exe (IL Disassembler) kullanabilirsiniz.