同时接受int[]和List<int>的方法

6

问题:编写一个单一的方法声明,能够接受 List<int>int[] 两种类型。

我的答案大概是这样的:

void TestMethod(object param) // 因为 object 是可以接受 int[] 和 List<int> 两种类型的基类

但这不是预期的答案,她说了。

有没有什么想法可以得到该方法签名?


可能是 void TestMethod(IEnumerable<int> param) - Michael
2
我会要求更多的细节:您需要使用Count还是类似于数组的下标?如果是这样,请使用IList<T>。您需要使用任何特定的方法吗?如果不需要,您可以使用object。否则,请使用IEnumerable<int> - Matthew Watson
5个回答

7
您可以使用 IList<int>,它同时支持 int[]List<int>
void TestMethod(IList<int> ints)

通过这种方式,您仍然可以使用索引器或Count属性(是的,如果将其转换为IList<T>ICollection<T>,数组就有一个Count属性)。它是两种类型之间最大可能的交集,允许快速访问,使用for循环或其他支持的方法

请注意,即使某些方法可以被调用,例如Add,也不支持它们,如果您在数组上使用它,将在运行时收到NotSuportedException(“Collection was of a fixed size”)。


2
请注意,为了完整性,IList<int>将允许您调用.Add()方法,但如果您传递的是int[]而不是List<int>,则会引发运行时异常。 - Matthew Watson
一个数组有一个 Length 属性。你可以使用 array.Count(),但那是来自 LINQ 的扩展方法。 - Corak
@Corak:不,它也有一个通过IList<T> --> ICollection<T>Count属性。在它可见之前,你必须将其强制转换。 - Tim Schmelter
@MatthewWatson:但是你会得到一个有意义的“NotSupportedException”。如果您想提供一个处理数组作为输入参数的方法,那么您不需要使用不受支持的方法。 - Tim Schmelter
@MatthewWatson:我已经将它添加到我的答案中了。我只想尽可能保持列表/数组的“力量”,并且根据需要限制类型为数组和列表(IEnumerable<T>包括更多类型)。 - Tim Schmelter
显示剩余3条评论

3
这可能是正确的答案:
void TestMethod(IEnumerable<int> list)

怎么回事?试试这个:TestMethod(new int[]{1,2,3}); - Yair Nevet

2
您的方法可以像这样:

您的方法可以像这样:

private void SomeMethod(IEnumerable<int> values)

1

你可以尝试这个

 private void TestMethod(dynamic param)
 {
     // Console.Write(param);

     foreach (var item in param)
     {
       Console.Write(item);
     }
}

TestMethod(new int[] { 1, 2, 3 });
TestMethod(new List<string>() { "x","y","y"});

@InvernoMuto:我不知道那是什么意思,但一定是正确的 ;) - Tim Schmelter
@InvernoMuto 为什么不打开 VS 编译我的代码?然后检查一下输出结果? - Anik Islam Abhi

1
如何使用泛型:
public static void TestMethod<T>(IEnumerable<T> collection)
{
   foreach(var item in collection)
   {
      Console.WriteLine(item);
   }
}

并像这样使用它:
int[] intArray = {1,2};
List<int> intList = new List<int>() { 1,2,3};
int[] intArray = {1,2};
List<int> intList = new List<int>() { 1,2,3};

TestMethod(intArray);
TestMethod(intList);

string[] stringArray =  { "a","b","c"}
List<string> stringList = new List<string>() { "x","y","y"};

TestMethod(stringArray);
TestMethod(stringList);

现在你可以将任何类型传递给它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接