Array.CreateInstance与使用new运算符创建新的数组实例之间的区别 [英] Difference between Array.CreateInstance and using the new operator to create new array instance

查看:119
本文介绍了Array.CreateInstance与使用new运算符创建新的数组实例之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以看到以下两种在C#中实例化一个int数组的方法:

  1. 通过System.Array抽象类中的API:

    var arrayInstance = Array.CreateInstance(typeof(int), 4);
    

  2. 通过各种数组初始化语法:

    var arrayInstanceWithSyntax = new int[4];
    

以上两种方式是否完全相同?编译器是在编译时本身(在MSIL中)将第二种语法转换为第一种语法,还是在运行时发生CLR级别的JIT魔术,或者两种代码语法之间根本没有转换?

解决方案

它们肯定会创建相同类型的值,例如,不同于您调用Array.CreateInstance并创建具有非零下限的数组的情况.

但是,它们在IL方面并不相同-第一个只是方法调用,第二个使用newarr IL指令.

这里不需要任何"JIT魔术",只有两条路径可以创建相同的价值.

第一个变量的编译时类型仅为Array-您必须将其强制转换为int[],以使两段代码真正具有相同的结果.

在可能的情况下,我会始终使用"C#本机"数组创建语法-仅在出于某种原因(而不是在编译时知道,甚至通过通用类型参数知道)而拥有元素Type时,才使用Array.CreateInstance. ..或尝试创建一个可能具有非零下限的数组.

I can see following two ways of instantiating an int array in C#:

  1. Through an API in System.Array abstract class:

    var arrayInstance = Array.CreateInstance(typeof(int), 4);
    

  2. Through various array initialization syntax:

    var arrayInstanceWithSyntax = new int[4];
    

Are the above two ways absolutely identical? Does the compiler converts the second syntax into first syntax at compile time itself (present in MSIL) or there is some JIT magic at CLR level which happens at run time or there is no conversion at all between the two code syntax?

解决方案

They definitely create the same kind of value - unlike if you call Array.CreateInstance and create an array with a non-zero lower bound, for example.

However, they're not the same in terms of IL - the first is simply a method call, the second uses the newarr IL instruction.

There doesn't need to be any kind of "JIT magic" here - there are just two paths to create the same kind of value.

The compile-time type of your first variable is just Array though - you'd have to cast it to int[] for the two pieces of code to really have the same result.

I would always use the "C# native" array creation syntax where possible - only use Array.CreateInstance when you have an element Type for some reason (rather than knowing at compile time, even via a generic type parameter)... or if you're trying to create an array that may have a non-zero lower bound.

这篇关于Array.CreateInstance与使用new运算符创建新的数组实例之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆