zoukankan      html  css  js  c++  java
  • 如何用反射实现如下的泛型方法调用?

     

    1. 代码

     

    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

                            ));

                    }

                }

            }

        }

     

        class myGeneric<T>

        {

         public    void Show<U>(U u)

            {

                Console.WriteLine(u.ToString());

            }

     

         public void Show(T t)

         {

             Console.WriteLine(t.ToString());

         }

        }

    }

    2.         如何通过反射找到泛型方法 Show<U>(U u) MethodInfo

  • 相关阅读:
    Fegin参数使用总结
    navicat彻底卸载
    VM虚拟机win10无法联网,DNS配置问题
    Navicat15的安装及破解
    Docker 配置国内镜像源拉取prometheus,解决prometheus拉取特别慢的问题
    python中faker(生成随机数据)
    初探移动网站的架构和设计
    利用HTML5的一个重要特性 —— DeviceOrientation来实现手机网站上的摇一摇功能
    响应式Web设计(三):响应式Web设计的方法
    响应式Web设计(四):响应式Web设计的优化
  • 原文地址:https://www.cnblogs.com/hbb0b0/p/1574667.html
Copyright © 2011-2022 走看看