代码之家  ›  专栏  ›  技术社区  ›  Wesley Hill

创建托管.NET数组而不初始化为所有零

  •  1
  • Wesley Hill  · 技术社区  · 15 年前

    采用以下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 .

    1 回复  |  直到 15 年前
        1
  •  3
  •   Joel Coehoorn    15 年前

    您应该这样做:

    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);
     }