zoukankan      html  css  js  c++  java
  • 利用传入的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();
            }

        }
  • 相关阅读:
    移动端H5 QQ在线客服链接代码
    sql语句的优化技巧
    获取网页高度
    微信抽奖游戏
    H5中section和article标签之间的区别
    简易版九宫格相加数值相等
    两个单体内置对象_Global和Math
    特殊的引用类型
    引用类型-Array类型(二)~ 前端学习之路
    引用类型-Array类型~ 前端学习之路
  • 原文地址:https://www.cnblogs.com/nuaalfm/p/1397340.html
Copyright © 2011-2022 走看看