[英]Reflection - Getting the generic arguments from a System.Type instance
如果我有以下代碼:
MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();
如何通過查看類型變量找出實例化了哪個類型參數“anInstance”? 是否可以?
使用Type.GetGenericArguments 。 例如:
using System;
using System.Collections.Generic;
public class Test
{
static void Main()
{
var dict = new Dictionary<string, int>();
Type type = dict.GetType();
Console.WriteLine("Type arguments:");
foreach (Type arg in type.GetGenericArguments())
{
Console.WriteLine(" {0}", arg);
}
}
}
輸出:
Type arguments:
System.String
System.Int32
使用 Type.GetGenericArguments()。 例如:
using System;
using System.Reflection;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();
foreach (Type t in type.GetGenericArguments())
Console.WriteLine(t.Name);
Console.ReadLine();
}
}
public class MyType<T> { }
}
輸出:Int32
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.