简体   繁体   English

在C#中传递通用List <>

[英]Passing a generic List<> in C#

I am going brain dead on this; 我脑子里死了; I have several List' defined, based on specific classes (c1, c2, c3...). 我根据特定的类(c1,c2,c3 ......)定义了几个List'。 I have a method that will process information on these lists. 我有一个方法来处理这些列表上的信息。 What I want to do is pass in the specific list, but have the method accept the generic list, and then via typeof determine what specific work to do. 我想要做的是传递特定列表,但让方法接受通用列表,然后通过typeof确定要执行的具体工作。 I know its possible, but I cant seem to get the syntax right on the method side. 我知道它可能,但我似乎无法在方法方面获得正确的语法。 so, for example: 所以,例如:

List<c1> c1var;
List<c2> c2var;
List<c3> c3var;

some_method(c1var);
some_method(c2var);
some_method(c3var);

class some_thing
some_method(List<> somevar)
if typeof(somevar).name = x then
esle if typeof(somevar).name = y then....

How do I set up the parameter list for the method? 如何设置方法的参数列表?

thanks in advance R. Sanders 谢谢R.桑德斯

You need to declare some_method to be generic, as well. 您还需要声明some_method是通用的。

void SomeMethod<T>(List<T> someList)
{
    if (typeof(T) == typeof(c1))
    {
         // etc
    }
}

Careful with the use of typeof(typ1) == typeof(typ2). 小心使用typeof(typ1)== typeof(typ2)。 That will test to see if the types are equivalent disregarding the type hierarchy. 这将测试以查看类型是否等同于忽略类型层次结构。

For example: 例如:

typeof(MemoryStream) == typeof(Stream); // evaluates to false
new MemoryStream() is Stream; //evalutes to true

A better way to check to see if an object is of a type is to use the 'is' keyword. 检查对象是否属于某种类型的更好方法是使用'is'关键字。 An example is below: 一个例子如下:

public static void RunSnippet()
{
    List<c1> m1 = new List<c1>();
    List<c2> m2 = new List<c2>();
    List<c3> m3 = new List<c3>();

    MyMeth(m1);
    MyMeth(m2);
    MyMeth(m3);
}

public static void MyMeth<T>(List<T> a)
{
    if (a is List<c1>)
    {
        WL("c1");
    }
    else if (a is List<c2>)
    {
        WL("c2");
    }
    else if (a is List<c3>)
    {
        WL("c3");
    }
}   

在参数部分放入List然后尝试在代码switch(typeof(T){case typeof(int): break;})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM