首页 新闻 会员 周边

c#中string[][]与string[,]区别

0
悬赏园豆:100 [已解决问题] 解决于 2009-06-09 16:46

源代码:

public class Students
    {
        public int ClassID { get; set; }
        public string[][] StudentArray { get; set; }
    }

 private static string GetJsonString(Students student)
        {
            student.ClassID = 1001;
            List<string[]> list = new List<string[]>();
            list.Add(new string[] { "1", "Jim" });
            list.Add(new string[] { "2", "Tom" });
            list.Add(new string[] { "3", "Kite" });
            student.StudentArray = list.ToArray();
            JavaScriptSerializer js = new JavaScriptSerializer();
            string result = js.Serialize(student);
            return result;
        }

这是return的结果:{"ClassID":1001,"StudentArray":[["1","Jim"],["2","Tom"],["3","Kite"]]}  注:这个是我想要的结果。

这之前的代码:

public class Students
    {
        public int ClassID { get; set; }
        public string[,] StudentArray { get; set; }
    }

 private static string GetJsonString()
        {
            Students stu = new Students();
            stu.ClassID = 1001;
            stu.StudentArray = new string[,] { { "1", "Jim" }, { "2", "Tom" }, { "3", "Kite" } };
            JavaScriptSerializer js = new JavaScriptSerializer();
            string result = js.Serialize(stu);
            return result;
        }

这个return的结果是:{"ClassID":1001,"StudentArray":["1","Jim","2","Tom","3","Kite"]}

请各位大侠指点下,出现这样的结果是啥子造成的呢?

c#中string[][]与string[,]区别是什么?

问题补充: 咋这么多人看 就没有一个人给我指点迷经呢 老赵 你来帮帮忙呃!
极风酷酷的主页 极风酷酷 | 初学一级 | 园豆:180
提问于:2009-04-29 17:43
< >
分享
最佳答案
1

string[][] 是不规则的,可以理解成元素是 string[] 类型的一维数组

string[,] 是规则的,可以理解是个矩阵,每个元素都是 string 类型

可以假设,在 JsSerializer 里面有一个方法用 foreach 遍历处理 IEnumerable 的成员,那么你可以试一下代码:

string[][] jagger;
string[,] matrix;

foreach (var item1 in jagger){}
foreach (var item2 in matrix){}

不用运行,用 VS 的智能提示看看两个 var 分别是什么类型,你会发现 item1 的类型是 string[],item2 的类型是 string,这就可以理解 JsSerializer 处理 string[][] 和 string[,] 的行为了。

DiryBoy | 小虾三级 |园豆:639 | 2009-05-01 19:20
其他回答(2)
0

楼上比较正解……但是说人家不规则,这貌似………………

zcsor~流浪dè风 | 园豆:5 (初学一级) | 2009-05-06 17:14
0

c#中声明数组的两种不同方式。多维数组和锯齿数组(交错数组)。以二维为例:

1.type[][],二维数组,数组的是维度固定的,例如:
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
int[, ,] array3D = new int[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } };
2.type[,],锯齿数组(交错数组),例如:
    int[][] jaggedArray2 = new int[][]
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
}
具体的定义可以查阅c#书籍或者MSDN~

Frank Xu Lei | 园豆:1860 (小虾三级) | 2009-05-14 15:44
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册