What's the magic of arrays in C#

后端 未结 8 1094
生来不讨喜
生来不讨喜 2020-12-09 08:56
int[] a = new int[5];
string[] b = new string[1];

The types of both a and b inherit from the abstract System.Array<

8条回答
  •  爱一瞬间的悲伤
    2020-12-09 09:44

    [] is a syntax(syntatic sugar) for defining Arrays in c#. Maybe CreateInstance will be replaced at runtime

     Array a = Array.CreateInstance(typeof(int), 5); 
    

    is same as

    int[] a = new int[5];
    

    Source for CreateInstance (taken from reflector)

    public static unsafe Array CreateInstance(Type elementType, int length)
    {
        if (elementType == null)
        {
            throw new ArgumentNullException("elementType");
        }
        RuntimeType underlyingSystemType = elementType.UnderlyingSystemType as RuntimeType;
        if (underlyingSystemType == null)
        {
            throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "elementType");
        }
        if (length < 0)
        {
            throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
        }
        return InternalCreate((void*) underlyingSystemType.TypeHandle.Value, 1, &length, null);
    }
    

提交回复
热议问题