在 C# 中使用匿名类型创建对象文字时出现问题
我正在尝试构建 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"}
};
编译器抛出:
"An anonymous type cannot have multiple properties with the same name"
Stab in the dark 我猜它无法区分哪个属性属于哪个属性对于哪个匿名对象,我在使用 LINQ 时看到了类似的错误。
有没有更好的方法来完成我想做的事情?
编辑:这是在 VisualStudio 2010 和 .net Framework 4 中。 Bala R 的答案 似乎解决了以前版本的问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你能试试这个吗?
并且您应该能够像这样访问匿名类数组
Can you try this?
and you should be able to access the anonymous class array like this