gpt4 book ai didi

c# - 如何使用 .NET 1.1 在 C# 中合并两个未定义类型的数组

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:37 25 4
gpt4 key购买 nike

我正在尝试创建一个实用程序方法,它将接受两个数组作为参数,将它们合并在一起,并返回结果数组。丢弃重复项。

理想情况下,参数将接受任何数组类型,例如 int[] 或 string[]。

我正在使用 C# .NET 1.1,因此无法访问泛型或 Array.Resize()。

有没有更好的方法来合并两个数组,不知道它们的类型,但返回一个相同类型的数组?

此时,下面的代码返回一个object[]的数组。我希望返回的数组类型与参数匹配。

public static object[] MergeArrays(object[] dest, object[] src)
{
if (dest.GetType() != src.GetType())
return null; // The arrays are of different types

if (dest.Equals(src))
return dest; // Don't merge with self

// We now know there are two compatible and unique arrays
int delta = src.Length;

// Cycle through the passed materials and see if they already exist
for (int i = 0; i < src.Length; i++)
// Check to see if this material already exists
for (int j = 0; j < dest.Length; j++)
if (src[i] == dest[j])
{
// The material already exists, so we'll skip it
src[i] = null;
delta--;
break;
}

// If there are still objects to merge, increase the array size
if (delta > 0)
{
object[] = new object[dest.Length + delta];
int index;

// Copy the original array
for (index = 0; index < dest.Length; index++)
tmp[index] = dest[index];

// Add the new elements
for (int i = 0; i < src.Length; i++)
{
if (src[i] == null)
continue;
tmp[index++] = src[i];
}
dest = tmp;
}
return dest;
}

最佳答案

我相信这在 .NET 1.1 中是合法的:

public static object[] Merge(object[] first, object[] second) {
if (first == null) {
throw new ArgumentNullException("first");
}
if (second == null) {
throw new ArgumentNullException("second");
}
Type firstType = first.GetType();
Type secondType = second.GetType();
if (firstType != secondType) {
throw new InvalidOperationException("type mismatch");
}
Hashtable table = new Hashtable();
ArrayList items = new ArrayList();
NewMethod(first, table, items);
NewMethod(second, table, items);
return (object[])items.ToArray(firstType.GetElementType());
}

static void NewMethod(object[] array, Hashtable table, ArrayList items) {
for (int i = 0; i < array.Length; i++) {
object item = array[i];
if (!table.Contains(item)) {
table.Add(item, 1);
items.Add(item);
}
}
}

我懒得为 NewMethod 找一个好名字,所以我只是让 Visual Studio 在提取到方法过程之后默认命名它。

用法:

object[] a = new string[10];
object[] b = new string[10];

for(int i = 0; i < 10; i++) {
a[i] = i.ToString();
b[i] = (i + 5).ToString();
}

object[] c = Merge(a, b);
Console.WriteLine(c.Length);
Console.WriteLine(c.GetType());
for (int i = 0; i < c.Length; i++) {
Console.WriteLine(c[i]);
}

输出:

15
System.String[]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

请注意,如果你想将两个 T[] 中的数组 T : ValueType 放入 Merge 中,你必须先将元素装箱并将数组键入 object[];这是因为当 T : ValueType 时,没有从 T[]object[] 的转换。此外,因为 GetType 不是虚拟的,所以在这种情况下您能得到的最好结果是 object[],而不是 T[] .

关于c# - 如何使用 .NET 1.1 在 C# 中合并两个未定义类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2242541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com