当前位置:编程学习 > C#/ASP.NET >>

如何用反射实现如下的泛型方法调用?

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

namespace GenericReflectingApp1

{

    class Program

    {

        static void Main(string[] args)

        {

            myGeneric<string> myString = new myGeneric<string>();

 

            myString.Show<int>(100);

 

            ShowTypeInfo(myString.GetType());

 

            //出现错误,"发现不明确的匹配。",

            //MethodInfo myMethod = myString.GetType().GetMethod("Show");

 

            //如何指定泛型方法参数

            //MethodInfo myMethod = myString.GetType().GetMethod("Show", new Type[] { });

 

            //Console.WriteLine (string.Format ("Is Generic Method:{0}",   myMethod .IsGenericMethod.ToString ()));

            Console.Read();

        }

 

        static void ShowTypeInfo(Type t)

        {

            Console.WriteLine(string.Format("TypeName:{0} Method List:", t.Name));

 

            foreach (MethodInfo obj in t.GetMethods())

            {

 

                Console.WriteLine(string.Format("Method Name:{0};IsGeneric Method:{1} ;ContainsGenericParameters:{2} ",

                    obj.Name, obj.IsGenericMethod.ToString(),obj.ContainsGenericParameters.ToString()));

 

                if (obj.GetGenericArguments().Count() > 0)

                {

                    Console.WriteLine(string.Format("Generic Arguments s count:{0}", obj.GetGenericArguments()[0].Name

                        ));

                }

            }

        }

  &nbs

补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,