Csharp/CSharp Tutorial/Reflection/Generic Type — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 18:31, 26 мая 2010
Reflection with Generics
<source lang="csharp">using System; using System.Reflection; public class Program {
static void Main() { Type type; type = typeof(System.Nullable<>); Console.WriteLine(type.ContainsGenericParameters); Console.WriteLine(type.IsGenericType); type = typeof(System.Nullable<DateTime>); Console.WriteLine(!type.ContainsGenericParameters); Console.WriteLine(type.IsGenericType); }
}</source>
Type: MakeGenericType
<source lang="csharp">using System; using System.Collections.Generic; public class MainClass {
static void Main() { IList<int> intList = (IList<int>) CreateClosedType<int>( typeof(List<>) ); IList<double> doubleList = (IList<double>) CreateClosedType<double>( typeof(List<>) ); Console.WriteLine( intList ); Console.WriteLine( doubleList ); } static object CreateClosedType<T>( Type genericType ) { Type[] typeArguments = { typeof( T ) }; Type closedType = genericType.MakeGenericType( typeArguments ); return Activator.CreateInstance( closedType ); }
}</source>
System.Collections.Generic.List`1[System.Int32] System.Collections.Generic.List`1[System.Double]
Using Reflection with Generic Types
<source lang="csharp">using System; using System.Collections.Generic; public class Program {
public static void Main() { Stack<int> s = new Stack<int>(); Type t = s.GetType(); foreach(Type types in t.GetGenericArguments()) { System.Console.WriteLine( "Type parameter: " + types.FullName); } // ... }
}</source>