在C#中使用匿名类型创建对象文字时出现问题 [英] Issues creating object literal using anonymous types in c#

查看:134
本文介绍了在C#中使用匿名类型创建对象文字时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建要传递给asp.net MVC中的视图模型的JavaScript对象文字的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:

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"

在黑暗中刺死我猜想它无法区分哪个属性与哪个匿名对象一起使用,我已经看到了使用LINQ的类似错误.

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?

这是在VisualStudio 2010和.net Framework 4中.

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

推荐答案

可以尝试吗?

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")
{
   ...
}

这篇关于在C#中使用匿名类型创建对象文字时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆