【问题标题】:Reflection - Getting the generic arguments from a System.Type instance反射 - 从 System.Type 实例获取通用参数
【发布时间】:2008-11-16 14:08:31
【问题描述】:

如果我有以下代码:

MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();

如何通过查看类型变量来找出实例化“anInstance”的类型参数?有可能吗?

【问题讨论】:

    标签: c# .net reflection generic-type-argument


    【解决方案1】:

    使用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
    

    【讨论】:

      【解决方案2】:

      使用 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 1970-01-01
        • 2021-03-23
        • 1970-01-01
        • 1970-01-01
        • 2013-12-16
        相关资源
        最近更新 更多