Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建托管.NET阵列而不初始化为全零_.net_Arrays - Fatal编程技术网

创建托管.NET阵列而不初始化为全零

创建托管.NET阵列而不初始化为全零,.net,arrays,.net,Arrays,采取以下C#方法: 静态双[]添加数组(左双[]右双[]双) { if(left.Length!=right.Length){ 抛出新ArgumentException(“要添加的数组长度不同”); } double[]结果=新的double[left.Length]; for(int i=0;i

采取以下C#方法:

静态双[]添加数组(左双[]右双[]双)
{
if(left.Length!=right.Length){
抛出新ArgumentException(“要添加的数组长度不同”);
}
double[]结果=新的double[left.Length];
for(int i=0;i
据我所知,CLR将初始化
result
为全零,即使
AddArrays
即将完全初始化它。有没有办法避免这些额外的工作?即使这意味着使用不安全的C#、C++/CLI或原始IL代码


编辑:无法执行,原因如下。

您应该改为执行此操作:

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

请参阅:不幸的是,我最终确实需要数组形式的结果,尽管这让我知道在我的情况下延迟计算可以工作多长时间(例如,将两个运算符合并为一个实现的操作)。
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");
    }
}
 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);
 }