本文介绍了帮助分配和使用匿名数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分配和使用匿名数组

我有一个对象,该对象在运行时可以是未知Type的数组.如果我知道数组Type,我有一个函数可以将数组转换为字符串泛型.但是我并不总是知道Type的到来.这是一个代码段:

Assigning and Using Anonymous Arrays

I have an object that at runtime can be an array of unknown Type. I have a function that will convert an array to a string generic if I know its Type. But I don''t always know the Type coming in. Here is a code snippet:

object val = getter.Invoke(obj, null);
                
string sval;

if (val == null)
    sval = "[Null]";
else
{
    Type t = val.GetType();
    if (t.IsArray == true)
    {
        object[] array = val as object[];
        sval = ArrayToStringGeneric(array, ", ");
    }
else
    sval = val.ToString();
}


当我尝试将val分配给类似于上述数组的数组时,出现并且对ArrayToStringGeneric的调用失败.如果我更改行:


When I try to assign val to array like above array come up null and my call to ArrayToStringGeneric fails. If I change the line:

object[] array = val as object[];


至:


to:

int[] array = val as int[];


分配有效,并且数组具有有效的值,但我并不总是知道Type.有没有一种方法可以在运行时使所有未知的Type正常工作?

谢谢,
E


The assignment works and array has values that work, but I will not always know the Type. Is there a way to make this work for all unknown Types at runtime?

Thanks,
E

推荐答案

// Your initial array stored in an object.
object o = new int[] { 1, 2, 3 };

// Cast to array.
Array a = (Array)o;

// Create object array to hold items.
object[] items = new object[a.Length];

// Move items to object array.
for (int i = 0; i < a.Length; i++)
{
    items[i] = a.GetValue(i);
}

// Show result.
for (int j = 0; j < items.Length; j++)
{
    MessageBox.Show(items[j].ToString());
}



这篇关于帮助分配和使用匿名数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 22:19