【发布时间】:2012-06-25 09:32:23
【问题描述】:
我想要一个映射函数来做到这一点:
public static void Map<T>(IEnumerable<T> src, params T[] dst)
{
for (int i = 0; i < dst.Length; i++)
dst[i] = src.ElementAt(i);
}
为了使这项工作 dst 还必须被声明为 ref,这似乎是不可能的。
这里用于一个虚构的单元测试:
int a = 0, b = 0, c = 0;
int[] arr = { 1, 2, 3 };
Tools.Map(arr, a, b, c);
Assert.AreEqual(a, 1);
Assert.AreEqual(b, 2);
Assert.AreEqual(c, 3);
这可能吗?它已经存在了吗?会不会是个坏主意?
编辑:换句话说,我如何给这个实现任意数量的参数:
public static void Map3<T>(IEnumerable<T> src, ref T a, ref T b, ref T c)
{
a = src.ElementAt(0);
b = src.ElementAt(1);
c = src.ElementAt(2);
}
【问题讨论】:
-
是的,这里有很多不好的东西,甚至在你的坏主意之前;p 首先,你在复制现有的功能。 (
Enumerable.ToArray())。 -
没有。转换不是从 IEnumerable 到数组,而是从 IEnumerable 到任意数量的单独变量。
-
看不出将数组设为
ref会有什么不同。您没有在函数中为实际数组分配新值。 -
@poingpoing:这毫无意义。
-
请查看我更新的问题。