在 C# 中传递通用 List<>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2051067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:01:39  来源:igfitidea点击:

Passing a generic List<> in C#

c#genericslist

提问by RockySanders99

I am going brain dead on this; I have several List' defined, based on specific classes (c1, c2, c3...). 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. I know its possible, but I cant seem to get the syntax right on the method side. so, for example:

我快要死了;我根据特定的类(c1、c2、c3...)定义了几个 List'。我有一种方法可以处理这些列表上的信息。我想要做的是传入特定列表,但让方法接受通用列表,然后通过 typeof 确定要执行的特定工作。我知道这是可能的,但我似乎无法在方法方面获得正确的语法。所以,例如:

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. Sanders

采纳答案by JSB????

You need to declare some_methodto be generic, as well.

您还需要声明some_method为泛型。

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

回答by GxG

in the parameter section put List then try in the code switch(typeof(T){case typeof(int): break;})

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

回答by Brian Hasden

Careful with the use of typeof(typ1) == typeof(typ2). That will test to see if the types are equivalent disregarding the type hierarchy.

小心使用 typeof(typ1) == typeof(typ2)。这将测试以查看类型是否等效,而不管类型层次结构。

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. An example is below:

检查对象是否属于某种类型的更好方法是使用“is”关键字。一个例子如下:

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