c#如何从对象中获取结果字符串

时间:2021-11-12 21:36:00

some c# code like:

一些c#代码如下:

Array arr=Array.CreateInstance(typeof(oject),3);
bool b=true;
int i =2;
float[] foo={1.1f,2.2f};
arr.setValue(b,0);
arr.setValue(i,0);
arr.setValue(foo,0);
string str=GetParamStringFromArrayObject(arr.GetValue(3));

string GetParamStringFromArrayObject(object obj)
{
if(obj.GetType().IsArray)
{
int demesion=obj.GetType().GetRank();//error,how to get the demesion(should be 2)
return obj.ToString();//error,i want to return the string delimeter by ' ' of   the float array,how to do?
}
}

as above code ,if i want the the string from the object which value is a array,how can i get it,and how to get the demesion of the array oject?

如上面的代码,如果我想从对象的字符串中获取值是一个数组,我怎么能得到它,以及如何得到数组的demesion?

thanks very much.

非常感谢。

2 个解决方案

#1


0  

You have to cast the object as an array, like this:

您必须将对象转换为数组,如下所示:

string GetParamStringFromArrayObject(object obj)
{
   Array array = obj as Array;
   if (array != null)
   {
       int demesion = array.Rank;
       // etc.
    }
}

#2


0  

if(obj is Array)
{
   int size = (obj as Array).Length; // get size
   string items = ""; // get string
   foreach (object item in obj as Array)
     items += item.ToString() + ",";
}

#1


0  

You have to cast the object as an array, like this:

您必须将对象转换为数组,如下所示:

string GetParamStringFromArrayObject(object obj)
{
   Array array = obj as Array;
   if (array != null)
   {
       int demesion = array.Rank;
       // etc.
    }
}

#2


0  

if(obj is Array)
{
   int size = (obj as Array).Length; // get size
   string items = ""; // get string
   foreach (object item in obj as Array)
     items += item.ToString() + ",";
}