我有一个二维数组,需要将其转换为字符串表示形式,并恢复为数组格式。我想创建一个通用方法来处理任何数组,例如1d,2d,3d等,以便今后可以重用该方法。
请问如何最好地实现这一目标?
请问如何最好地实现这一目标?
string[,] _array = new string[_helpTextItemNames.Count, 2];
public static class Helpers
{
public static string ObjectToString(Array ar)
{
using (MemoryStream ms = new MemoryStream())
{
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(ms, ar);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
public static object ObjectFromString(string s)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(s)))
{
SoapFormatter formatter = new SoapFormatter();
return formatter.Deserialize(ms) as Array;
}
}
public static T ObjectFromString<T>(string s)
{
return (T)Helpers.ObjectFromString(s);
}
}
// Serialize a 1 dimensional array to a string format
char[] ar = { '1', '2', '3' };
Console.WriteLine(Helpers.ObjectToString(ar));
// Serialize a 2 dimensional array to a string format
char[,] ar2 = {{ '1', '2', '3' },{ 'a', 'b', 'c' }};
Console.WriteLine(Helpers.ObjectToString(ar2));
// Deserialize an array from the string format
char[,] ar3 = Helpers.ObjectFromString(Helpers.ObjectToString(ar2)) as char[,];
char[,] ar4 = Helpers.ObjectFromString<char[,]>(Helpers.ObjectToString(ar2));
据我所知,您拥有一个二维数组[n列 x n行]。您想将其转换为字符串,然后再将此字符串转换回二维数组。我有一个如下的想法:
//The first method is convert matrix to string
private void Matrix_to_String()
{
String myStr = "";
Int numRow, numCol;//number of rows and columns of the Matrix
for (int i = 0; i < numRow; i++)
{
for (int j = 0; j < numCol; j++)
{
//In case you want display this string on a textbox in a form
//a b c d . . . .
//e f g h . . . .
//i j k l . . . .
//m n o p . . . .
//. . . . . . . .
textbox.Text = textbox.Text + " " + Matrix[i,j];
if ((j == numCol-1) && (i != numRow-1))
{
textbox.Text = textbox.Text + Environment.NewLine;
}
}
}
myStr = textbox.text;
myStr = myStr.Replace(" ", String.Empty);
myStr = myStr.Replace(Environment.NewLine,String.Empty);
}
//and the second method convert string back into 2d array
private void String_to_Matrix()
{
int currentPosition = 0;
Int numRow, numCol;//number of rows and columns of the Matrix
string Str2 = textbox.Text;
Str2 = Str2 .Replace(" ", string.Empty);
Str2 = Str2 .Replace(Environment.NewLine, string.Empty);
for (int k = 0; k < numRow && currentPosition < Str2 .Length; k++)
{
for (int l = 0; l < numCol && currentPosition < Str2 .Length; l++)
{
char chr = Str2 [currentPosition];
Matrix[k, l] = chr ;
currentPosition++;
}
}
}
Array.GetValue
和Array.SetValue
需要特定的形式。这里是StringFromArray
,我会把ArrayFromString
留作练习(它只是一个带有一些解析的反向操作)。请注意,下面的代码仅适用于矩形数组。如果您想支持不规则数组,那就完全不同了,但至少要简单得多。您可以通过检查array.GetType()
是否为Array
来判断数组是否为不规则数组。它还不支持下限不为零的数组。对于C#来说,这没有任何意义,但这意味着它可能无法作为通用库从其他语言中使用。这可以修复,但我认为这不值得花费这个代价。[删除关于非零基数组的粗话]static string StringFromArray(Array array)
{
int rank = array.Rank;
int[] lengths = new int[rank];
StringBuilder sb = new StringBuilder();
sb.Append(array.Rank.ToString());
sb.Append(':');
for (int dimension = 0; dimension < rank; dimension++)
{
if (array.GetLowerBound(dimension) != 0)
throw new NotSupportedException("Only zero-indexed arrays are supported.");
int length = array.GetLength(dimension);
lengths[dimension] = length;
sb.Append(length);
sb.Append(':');
}
int[] indices = new int[rank];
bool notDone = true;
NextRank:
while (notDone)
{
notDone = false;
string valueString = (array.GetValue(indices) ?? String.Empty).ToString();
sb.Append(valueString.Length);
sb.Append(':');
sb.Append(valueString);
for (int j = rank - 1; j > -1; j--)
{
if (indices[j] < (lengths[j] - 1))
{
indices[j]++;
if (j < (rank - 1))
{
for (int m = j + 1; m < rank; m++)
indices[m] = 0;
}
notDone = true;
goto NextRank;
}
}
}
return sb.ToString();
}