简体   繁体   English

以列表为参数的重载函数

[英]Overload Function with List as a Parameter

I want to create a function with C# List datatype as a parameter. 我想用C#List数据类型作为参数创建一个函数。

public void foo(List<Something> obj)
{
...
}

But I want to pass anykind of List type to the function, I mean, like this 但是我想将任何类型的List类型传递给函数,我的意思是像这样

List<Class1> obj1 = new List<Class1>();
foo(obj1);

List<Class2> obj2 = new List<Class2>();
foo(obj2);

Can I do something like this? 我可以做这样的事情吗? How to do this? 这个怎么做? Thanks in advance 提前致谢

Add a generic argument to your foo method. 在您的foo方法中添加一个通用参数。

public void foo<T>(List<T> obj)
{
...
}

You can find more about them here . 您可以在此处找到有关它们的更多信息。

use generics . 使用泛型

public void foo<T>(List<T> obj)
{
...
}

call like

 foo<Class1>(new List<Class1>());
 foo<Class2>(new List<Class2>());

The above can be simplified further to by making use of generics type inference 通过使用泛型类型推断 ,可以进一步简化上述内容

 foo(new List<Class1>());
 foo(new List<Class2>());

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

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