【问题标题】:Howto someFunction(List<acceptDifferentTypesHere> list) { /*reflection stuff*/ }如何使用 someFunction(List<acceptDifferentTypesHere> list) { /*reflection stuff*/ }
【发布时间】:2012-01-18 15:13:36
【问题描述】:

我想从列表中生成一个数据表。

所以 f.e.我有两个列表

List<typeA> listA = new List<typeA>(); 
List<typeB> listB = new List<typeB>();

我怎样才能获得一个函数接受两个(或多个)具有不同元素类型的列表?

private void someFunction(List<acceptDifferentTypesHere> list)
{ 
   /*elementwise reflection stuff*/
} 

任何帮助都会很好,

哈利

【问题讨论】:

  • 编译时你知道 typeA 还是 typeB 吗?

标签: c# asp.net function collections


【解决方案1】:
private void someFunction<T>(List<T> list)
{ 
   /*elementwise reflection stuff*/
}

如下使用

someFunction<typeA>(listA);
someFunction<typeB>(listB);

【讨论】:

  • 它喊道:“扩展方法必须在非泛型静态类中定义”
  • 您没有使用扩展方法,或者您没有显示导致错误的代码
  • @Harry 确保选择此作为接受的答案,然后:D
【解决方案2】:

如果您想对不同类型(访问方法、属性)做更多事情。

 private void someFunction<T>(List<T> list) where T : MyType, new()
    { 
       /*elementwise reflection stuff*/

       var instance = new T();
       Type type = instance.GetType();
       instance.MyMethod();    
    } 

    public class MyType
    {        
       public void MyMethod()
       {

       }
    }

您可以进一步扩展它..(例如,使用 MyType 作为 typeA 和 typeB .. 等的概括)

【讨论】:

    猜你喜欢
    • 2021-05-22
    • 2021-12-26
    • 2022-01-25
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    相关资源
    最近更新 更多