1

We have in PHP the jagged array declaration is like this:

<?php
$classmates = array ('Name' => array ('Bob', 'Jane', 'Jill'),
                    'Age' => array (18, 20, 23));

echo $classmates['Name'][1] . ' is ' . $classmates['Age'][1] . ' years old!';
?>

can we do same initialization of array in C#??

If yes than how? also tell me if it is possible to do with data type List?

4

1 回答 1

2

好吧,从字面上讲,你可以在 C# 中做这样的事情:

    var arr = new Array[] { 
        new[] {"Bob", "Jane", "Jill"},
        new[] { 18,20,23 }};

我会说这可能不是一个好主意。在 C# 中,这样说会更好:

var arr = new[] { 
    new Person {Name = "Bob", Age = 18},
    new Person {Name = "Jane", Age = 20},
    new Person {Name = "Jill", Age = 23}};

或者,如果您不打算创建实际的 Person 类,则可以使用匿名类:

var arr = new[] { 
    new {Name = "Bob", Age = 18},
    new {Name = "Jane", Age = 20},
    new {Name = "Jill", Age = 23}};

你所学的课程取决于你将如何使用数组,但只要说第一次使用在大多数用例中并不被认为是最佳实践就足够了。

于 2013-06-01T02:15:11.340 回答