• 利用传入的Type类型来调用范型方法的解决方案


    起因:自定义一个GridView控件,其数据源来源于一个通用方法Get<T>(),根据你传入的T到数据库中得到相应的数据,问题是定义GridView控件时没法在界面端设置使用泛型,只能在每个使用这个GridView控件时绑定数据。如果你没看懂这个起因也没关系,我们用一段代码来描述一下问题:
    我希望使用的是从外边传过来的类型tt来调用test1范型方法

    class Program 
        { 
            
    static void Main(string[] args) 
            { 
                MyClass m 
    = new MyClass(); 
                m.tt 
    = typeof(Program); 
                m.test2(); 
            } 
            

        } 

        
    class MyClass 
        { 
            
    public Type tt { getset; } 
            
    public int userid { getset; } 
            
    public string Name { getset; } 
            
    public string test2() 
            { 
              
    // test1 <T>(); 
              我希望使用的是从外边传过来的类型tt来调用test1范型方法 
            } 
            
    public string test1 <T>() 
            { 
                
    return typeof(T).ToString(); 
            } 
            
        }

    解决方案:

    class MyClass
        {
            
    public Type tt { getset; }
            
    public int userid { getset; }
            
    public string Name { getset; }
            
    public string test2() 
            { 
                
    object result = typeof(MyClass).GetMethod("test1").
                    MakeGenericMethod(tt).Invoke(
    thisnull);
                
    return result.ToString();
            }
            
    public string test1<T>()
            {
                
    return typeof(T).ToString();
            }

        }
  • 相关阅读:
    centos中pipelinedb安装及初步使用
    sqlalchemy 的操作
    存储引擎,索引,慢日志,权限管理
    python使用mysql
    mysql数据库查找数据的方法。
    mysql 数据库的基本操作
    epoll 数据库安装以及相关概念
    IO模型,非阻塞IO模型,select实现多路复用
    线程回调,线程中的队列,事件,greenlet模块,gevent模块,自定义补丁, 单线程实现并发,协程
    GIL全局解释器锁,线程池与进程池 同步异步,阻塞与非阻塞,异步回调
  • 原文地址:https://www.cnblogs.com/nuaalfm/p/1397340.html
Copyright © 2020-2023  润新知