C# 有没有一种方法可以声明非零下限数组 typeof(dynamic)

C# Is there a way of declaring non zero lower bound array typeof(dynamic)

我需要它来连接 vb6 库,它期望输出数组的形式对数据进行一些计算。是否有任何形式的解决方法,因为我不能仅在数组声明中使用语句 typeof(dynamic) typeof(object)...

目前我尝试过的:

System.Array Outputs = Array.CreateInstance(typeof(Object), 1);
System.Array Outputs = Array.CreateInstance(typeof(object), 1);
System.Array Outputs = Array.CreateInstance(typeof(dynamic), 1); // Compilation error

dynamic 实际上只存在于编译时。例如,如果您创建一个 List<dynamic>,那实际上是在创建一个 List<object>。因此,使用 typeof(dynamic) 没有意义,这就是第三行编译失败的原因。如果您将数组传递给其他代码,则取决于其他代码如何使用数组 - 在执行时 "know" 没有任何内容可以动态输入。

但是为了创建数组,您必须提供 长度。您使用的 Array.CreateInstance 的重载始终使用零下限。您希望重载接受两个 arrays 整数 - 一个用于长度,一个用于下限。例如:

using System;

class Program
{
    static void Main()
    {
        Array outputs = Array.CreateInstance(
            typeof(object), // Element type
            new[] { 5 },    // Lengths                                             
            new[] { 1 });   // Lower bounds

        for (int i = 1; i <= 5; i++)
        {
            outputs.SetValue($"Value {i}", i);
        }
        Console.WriteLine("Set indexes 1-5 successfully");
        // This will throw an exception
        outputs.SetValue("Bang", 0);        
    }
}