Issues creating object literal using anonymous types in c#

人走茶凉 提交于 2019-12-10 10:26:47

问题


I'm trying to build the c# approximation of a JavaScript object literal to be passed to a view model in asp.net MVC:

var obj = new dynamic[]{
    new { name: "Id", index: "Id", width: 40, align: "left" },
    new { name: "Votes", index: "Votes", width: 40, align: "left" },
    new { name: "Title", index: "Title", width: 200, align: "left"}
};

The compiler is throwing:

"An anonymous type cannot have multiple properties with the same name"

Stab in the dark I'm guessing it can't distinguish between the which property goes with which anonymous object, I've seen a similar error using LINQ.

Is there a better way to accomplish what I'm trying to do?

EDIT: This is in VisualStudio 2010 and .net Framework 4. Bala R's Answer seems to address the problem for previous versions though.


回答1:


Can you try this?

var obj = new[]{
    new { name= "Id", index= "Id", width= 40, align= "left" },
    new { name= "Votes", index= "Votes", width= 40, align= "left" },
    new { name= "Title", index= "Title", width= 200, align= "left"}
};

and you should be able to access the anonymous class array like this

if (obj[0].align == "left")
{
   ...
}


来源:https://stackoverflow.com/questions/5795296/issues-creating-object-literal-using-anonymous-types-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!