在 c# 中采用任何类型的可索引列表的方法的最有效方法是什么

What's the most efficient way to have a method that takes an indexable list of any type in c#

我希望能够在 C# 中编辑任何或大部分使用索引器的通用列表类型,如下所示:

void testIList(System.Collections.IList someList)
{
    for (int i = 0; i < someList.Count; i++)
    {
        someList[i] = someList.Count - i;
    }
}

void test()
{
    int[] intArray = new int[10];
    List<int> intList = new List<int>();
    List<string> stringList = new List<string>();

    for(int i=0;i<10;i++)
    {
        intList.Add(0);
        stringList.Add("test");
    }

    testIList(intArray);
    testIList(intList);

    testIList(stringList);
}

代码有效,但当然没有 testIList(stringList) 的编译时错误,这是不希望出现的。

此外,我可以通过使用一些更具体的通用集合作为参数中的类型来避免在 testIList 中发生装箱和拆箱吗?

使用 IList 的通用接口:IList<T>:

void testIList<T>(System.Collections.Generic.IList<T> someList)
{
    for (int i = 0; i < someList.Count; i++)
    {
        someList[i] = default(T);
    }
}

当然,您必须自己找出确定列表项设置值的逻辑是什么,但至少 default(T) 会告诉您代码有效。

您可以使用 System.Collections.Generic.IList<T> 接口只允许实现该接口的那些集合,即 List<int>int[] 和其他一些集合。它不允许像 ArrayListList<object> 这样的非通用列表类型(您当前的代码可以使用它们),但阻止它通常是一件好事而不是坏事。

void TestIList(IList<int> someList)
{
    for (int i = 0; i < someList.Count; i++)
    {
        someList[i] = someList.Count - i;
    }
}