C#有没有办法声明非零下界数组的类型(动态)

问题描述 投票:0回答:1

我需要它来连接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
c# vb6-migration
1个回答
1
投票

dynamic真的只存在于编译时。例如,如果你创建一个List<dynamic>,那真的是在创建一个List<object>。因此,使用typeof(dynamic)没有意义,这就是第三行无法编译的原因。如果你将数组传递给其他代码,则由其他代码决定它是如何使用数组的 - 在执行时没有任何东西可以“知道”它是动态类型的。

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

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);        
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.