在 C# 中使用匿名类型创建对象文字时出现问题

发布于 2024-11-03 14:52:12 字数 742 浏览 3 评论 0原文

我正在尝试构建 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

染火枫林 2024-11-10 14:52:12

你能试试这个吗?

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"}
};

并且您应该能够像这样访问匿名类数组

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

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")
{
   ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文