对参数的不同操作可能是数组

本文关键字:数组 操作 参数 | 更新日期: 2023-09-27 17:53:35

这里T可以是一个数组或单个对象。如何将数组添加到数组列表或将单个对象添加到同一个数组列表。这给了我一个构建时错误,即AddRange的重载匹配具有无效参数。

T loadedContent;
if (typeof(T).IsArray)
{
    contentArrayList.AddRange(loadedContent);
}
else
{
    contentArrayList.Add(loadedContent);
}

对参数的不同操作可能是数组

编辑:在检查了有关转换为Array类型的一些规则后,更正了我的答案。

所有特定类型的数组,如int[], string[],或MyCustomObject[],都是从基本的Array类派生出来的,因此,它们实现了ICollection接口,这是ArrayList.AddRange方法接受的参数。

假设您的contentArrayList变量是ArrayList对象,您应该能够将您的loadedContent变量强制转换为ICollection:

contentArrayList.AddRange((ICollection)loadedContent)

或者,您可以将检查它是否为数组与强制转换结合起来:

Array loadedContentAsArray = loadedContent as Array;
if (loadedContentAsArray != null)
{
    contentArrayList.AddRange(loadedContentAsArray);
}

Dr. Wily's Apprentice提供的解决方案将有效,但我想做一些旁注。

如果你使用泛型,但你仍然致力于一个特定的数据类型,你的代码中一定有设计问题。基本上,您破坏了泛型的目的,如MSDN中所述:

泛型允许您定义类型安全的数据结构,而无需提交实际的数据类型。

也许你应该重新考虑一些重构,也许通过添加不同参数的方法或其他…

如果你的contentList类型是ArrayList,我就会这样做。

        ICollection contentArray = loadedContent as ICollection;
        if (contentArray != null)
            contentList.AddRange(contentArray);
        else
            contentList.Add(loadedContent);