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();
            }

        }
  • 相关阅读:
    iOS多线程的初步研究(十)-- dispatch同步
    iOS 几种定时器
    iOS 如何计算UIWebView的ContentSize
    iOS 如何计算UIWebView的ContentSize
    iOS: NSTimer使用小记
    iOS: NSTimer使用小记
    使用Objective-C的+(void)initialize初始化static变量
    使用Objective-C的+(void)initialize初始化static变量
    拒绝从入门到放弃_《Python 核心编程 (第二版)》必读目录
    拒绝从入门到放弃_《Python 核心编程 (第二版)》必读目录
  • 原文地址:https://www.cnblogs.com/nuaalfm/p/1397340.html
Copyright © 2011-2022 走看看