【问题标题】:Create managed .NET array without initializing to all zeros创建托管 .NET 数组而不初始化为全零
【发布时间】:2010-01-24 02:52:59
【问题描述】:

采用以下 C# 方法:

static double[] AddArrays(double[] left, double[] right)
{
    if (left.Length != right.Length) {
        throw new ArgumentException("Arrays to add are not the same length");
    }

    double[] result = new double[left.Length];
    for (int i = 0; i < left.Length; i++) {
        result[i] = left[i] + right[i];
    }

    return result;
}

据我了解,CLR 会将result 初始化为全零,尽管AddArrays 无论如何都将要完全初始化它。有什么办法可以避免这种额外的工作?即使这意味着使用不安全的 C#、C++/CLI 或原始 IL 代码?

编辑:由于here 所述的原因,无法完成。

【问题讨论】:

标签: .net arrays


【解决方案1】:

你应该这样做:

static IEnumerable<double> Add(IEnumerable<double> left, IEnumerable<double> right)
{ 
    using (IEnumerator<double> l = left.GetEnumerator())
    using (IEnumerator<double> r = right.GetEnumerator())
    {
        while (l.MoveNext() && r.MoveNext())
        {
            yield return l.Current + r.Current;
        }

        if (l.MoveNext() || r.MoveNext())
            throw new ArgumentException("Sequences to add are not the same length");
    }
}

您可以将双精度数组传递给此函数。如果你真的需要一个数组作为结果(提示:你可能不需要),你可以在函数的返回值上调用.ToArray()

.Net 4 将为此内置一个函数:

 double[] array1 = {1.0, 2.0, 3.0};
 double[] array2 = {4.0, 5.0, 6.0};
 IEnumerable<double> result = array1.Zip(array2, (a,b) => a + b);

 foreach(double d in result)
 {
     Console.WriteLine(d);
 }

【讨论】:

  • 不幸的是,我最终确实需要数组形式的结果,尽管这让我知道延迟评估在我的情况下可以工作多长时间(例如,将两个运算符组合成一个已实现的操作) .
猜你喜欢
  • 2014-03-13
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 2016-04-02
相关资源
最近更新 更多