利用传入的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();
        }

    }
posted @ 2009-02-24 16:27  你听海是不是在笑  阅读(830)  评论(0编辑  收藏  举报