public void GetModelList(List<T> list)
{
}我想定义一个类似于上面的方法,其参数是一个泛型集合,但是这个泛型集合的参数类型是不确定的。如我可以传如下参数:List<string> class1 = new List<string> ();
GetModelList(class1);
其类型可以用任何类型 List<int> 等.
我尝试用 public void GetModelList(List<object> list) {};
但是这样不行,这样我就必须要进行类型转换。
请大家给点意见,谢谢!

解决方案 »

  1.   

    泛型没办法这样用.你想实现这种功能就是重写(override)函数.
      

  2.   

    public void GetModelList<T>(List<T> list)
    {
       
    }
      

  3.   

    lz 去看看 MSDN 关于泛型方法滴解释吧!
    public void GetModelList<T>(List<T> listT) 

        foreach(T t in listT)
        {
            // t...
        }

      

  4.   

    ding ge  xian 
    我觉得泛型本来是要避免装箱拆箱的,现在为什么反而要传进去不确定的类型呢
      

  5.   


    public void GetModelList(System.Collections.IEnumerable list)
    {}
      

  6.   

    不明白楼主为什么要传泛型的不确定类型过去··如果你只是希望传不同类型可以使用
    (object sender)如果你需要传很多参数,你可以使用(paras[] para)如果你又需要类型又需要参数(object sender, EventArgs e)楼主的思维就有问题,泛型传过去,必须转换。。如果楼主想实现什么效果,最好,换个思路
      

  7.   

    泛型方法调用时是可以进行类型推论断的,参考:
    using System;class Test
    {
      static void Main()
      {
        Console.WriteLine(Max(1));                               // 输出: 1
        Console.WriteLine(Max(.3, -.5));                         // 输出: 0.3
        Console.WriteLine(Max(0M, -3M, 3.14M));                  // 输出: 3.14
        Console.WriteLine(Max(9f, -1f, 3.14f, -2.718f));         // 输出: 9
        Console.WriteLine(Max(0u, 23u, 3114u, 120718u, 5678u));  // 输出: 120718
      }  static T? Max<T>(params T[] x)
      where T: struct, IComparable
      {
        if (x.Length == 0) return null;
        T a = x[0];
        foreach (T i in x)
          if (a.CompareTo(i) < 0) a = i;
        return a;
      }
    }
      

  8.   

    using System.Collections.Generic;class class1{}class Test
    {
      static void Main()
      {
        List<string> class1 = new List <string>(); 
        GetModelList<string>(class1); // 这样可以
        GetModelList(class1);         // 这样也可以, 调用时会进行类型自动推断
      }  static void GetModelList<T>(List<T> list)
      {
      }
    }
      

  9.   

    上面程序k 的
    class class1{}
    应该去掉。
      

  10.   


    string xx="字符串"; 
    int a=20; 
    datetime dt=System.DateTime.Now; 
    smallint sint=20; 
    bit b=0x81; 
    bigint=20; ArrayList al=new ArrayList() 
    al.add(xx); 
    al.add(a); 
    你依此类add吧