在C#上从object []转换为double []

Gia*_*ini 3 c# arrays casting dynamic

我有一个函数生成具有不同数据的对象(该函数根据类型用随机数据填充对象).该函数返回一个object[]类型仅在运行时知道(并且它作为参数传递给函数).

double[] values;

values = factory.GetData(typeof(double), 10);
Run Code Online (Sandbox Code Playgroud)

不幸的是我收到编译错误:

无法从object []转换为double [].

如何以object[]编程方式进行转换?

编辑:

这是原始功能:

    public object[] GetData(Type type, int howMany)
    {
        var data = new List<object>();

        for (var i = 0; i < howMany; i++)
        {
            data.Add(Convert.ChangeType(GetRandom(type), type));
        }

        return data.ToArray();
    }
Run Code Online (Sandbox Code Playgroud)

在哪里GetRandom()创建一个类型的对象type并为其分配一个随机值(随机int,随机字符串,随机双精度,只有基本类型)

这是GetRandom()函数:

   public T GetRandom<T>()
    {
        var type = typeof(T);

        if (type == typeof(int))
        {
            return prng.Next(0, int.MaxValue);
        }

        if (type == typeof(double))
        {
            return prng.NextDouble();
        }

        if (type == typeof(string))
        {
            return GetString(MinStringLength, MaxStringLength);
        }

        if (type == typeof(DateTime))
        {
            var tmp = StartTime;
            StartTime += new TimeSpan(Interval * TimeSpan.TicksPerMillisecond);
            return tmp;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ofi*_*ris 6

使用Array.ConvertAll:

values =  Array.ConvertAll(factory.GetData(typeof(double), 10), item => (double)item);
Run Code Online (Sandbox Code Playgroud)

例:

object[] input = new object[]{1.0, 2.0, 3.0};
double[] output = Array.ConvertAll(input, element => (double)element); // [1.0, 2.0, 3.0]
Run Code Online (Sandbox Code Playgroud)

请注意,InvalidCastException如果其中一个项目无法转换为double,则可能会获得.