填充c#数组时出错

时间:2016-12-06 17:04:53

标签: c#

我正在尝试这样做,但会出现语法错误。有什么我做错了吗?我是否必须每次都制作一个特定的类来适应每个对象?

var groups = [
    { id: 1, name: 'Conversation' },
    { id: 2, name: 'Business' },
    { id: 27, name: 'Animals' }
];

2 个答案:

答案 0 :(得分:8)

那不是C#;尝试:

var groups = new [] {
    new { id = 1, name = "Conversation" },
    new { id = 2, name = "Business" },
    new { id = 27, name ="Animals" }
};

那说...与匿名类型一起工作很尴尬;您可能想要声明一个包含IdName的类型并改用它:

var groups = new [] {
    new Foo { Id = 1, Name = "Conversation" },
    new Foo { Id = 2, Name = "Business" },
    new Foo { Id = 27, Name ="Animals" }
};
...
class Foo {
     public int  Id {get;set;}
     public string Name {get;set;}
}

答案 1 :(得分:-1)

试试这个:

var groups = new object[] { new { id=1, name="Conversation" },
new { id=1, name="Conversation" },
new { id=1, name="Conversation" }
};