2010-09-04 90 views
2

我有一个二维数组,我需要能够转换为字符串表示形式并返回数组格式。我想创建一个generci方法来处理任何数组1d,2d,3d等,这样我可以在将来重用该方法。将多维数组转换为字符串并返回

这样做的最好方法是什么?

string[,] _array = new string[_helpTextItemNames.Count, 2]; 
+1

也许使用JSON – jerone 2010-09-04 14:18:45

+0

这不是一个坏主意,你可以给任何更多的细节? – Burt 2010-09-04 14:59:33

回答

2

如果您不太在乎字符串的结构,那么SoapFormatter是一个选项。这是一个快速而肮脏的例子。不漂亮,但它可能适合你。

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); 
    } 
} 

这些辅助函数可以用于任何Serializable对象变换为一个字符串,包括阵列,只要数组的元素是可序列化。

// 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)); 
+1

@Burt,您需要添加对'System.Runtime.Serialization.Formatters.Soap'程序集的引用。猜你发现它:) – 2010-09-04 15:26:32

+0

是啊:)现在就试试你的解决方案。不知道我是否会放弃格式,但会给它一个镜头。 – Burt 2010-09-04 15:41:30

+0

这个工作我打算让问题openb一段时间,看看是否有人提出任何其他事情。谢谢您的帮助。 – Burt 2010-09-05 13:57:46

1

如果你想determain自己的格式,最困难的部分只是走一个矩形阵列,因为Array.GetValueArray.SetValue期望的具体形式。这里是StringFromArray,我将作为练习离开ArrayFromString(这只是一个小解析而已)。请注意,下面的代码仅适用于矩形阵列。如果你想支持锯齿阵列,那完全不同,但至少要简单得多。您可以通过检查array.GetType()Array来判断阵列是否参差不齐。它也不支持数组下限是零以外的数组。对于C#来说,这并不意味着什么,但它确实意味着它可能不能用作其他语言使用的通用库。这可以是固定的,但它不值得入场国际海事组织的价格。这里使用的格式很简单: [num dimensions]:[length dimension#1]:[length dimension#2]:[...]:[[删除了非基于零的阵列的解释]

[字符串长度]:字符串值] [[字符串长度]:字符串值[...]

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(); 
} 
1

据我所知,你有一个二维数组[N的cols XN行。你想将它转换为字符串,然后你想将这个字符串转换回2d数组。我有一个想法如下:

//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++; 
        } 
       } 

      } 

希望这个帮助!