[英]Issues creating object literal using anonymous types in c#
I'm trying to build the c# approximation of a JavaScript object literal to be passed to a view model in asp.net MVC: 我正在尝试构建一个JavaScript对象文字的c#近似值,以传递给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. 在黑暗中刺戳我猜它无法区分哪个属性与哪个匿名对象,我看到使用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. 编辑:这是在VisualStudio 2010和.net Framework 4中.Bala R的答案似乎解决了以前版本的问题。
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")
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.