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

时间:2018-04-29 05:14:03

标签: c# vb6-migration

我需要它来连接vb6库,它希望输出数组的形式对数据进行一些计算。有没有任何形式的解决方法,因为我不能仅在数组声明select * from ABD where a=0 and b= 42 and c=(Select c from azs) or f=89 or x=10 中使用语句typeof(dynamic) ...

到目前为止我尝试过:

typeof(object)

1 个答案:

答案 0 :(得分: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);        
    }
}