如果我有这个:
SubMenuList=new object[]
{
new
{
transKey = "PERSONAL_INFORMATION",
stateName="account.personalinformation",
displayUrl = "/account/personalinformation"
},
new
{
tranKey = "NOTIFICATIONS",
stateName = "account.notificationsettings",
displayUrl = "/account/notifications"
}
}
我可以以某种方式向此添加if
语句并说出例如:
if (something != null)
{
new
{
transKey = "PERSONAL_INFORMATION",
stateName="account.personalinformation",
displayUrl = "/account/personalinformation"
}
}
答案 0 :(得分:1)
为此,最好使用List<Object>
:
var list = new List<object>
{
new
{
transKey = "PERSONAL_INFORMATION",
stateName="account.personalinformation",
displayUrl = "/account/personalinformation"
}
};
if (something != null)
{
list.Add(new
{
tranKey = "NOTIFICATIONS",
stateName = "account.notificationsettings",
displayUrl = "/account/notifications"
});
}
如果你想获得一个数组,你可以在链接上调用ToArray()
:
SubMenuList = list.ToArray();
最好在这里引入非匿名类型,因为这些对象具有相同的结构,没有上下文,很难猜出为什么不使用命名类型。
答案 1 :(得分:0)
您可以使用@DavidArno建议的实际类型列表,并在something != null
添加新项目到列表中。
您还可以使用匿名类型:
var list = new[]
{
new
{
transKey = "PERSONAL_INFORMATION",
stateName="account.personalinformation",
displayUrl = "/account/personalinformation"
},
new
{
transKey = "NOTIFICATIONS",
stateName = "account.notificationsettings",
displayUrl = "/account/notifications"
}
}.ToList()
if (something != null)
{
list.Add(new
{
transKey = "PERSONAL_INFORMATION",
stateName="account.personalinformation",
displayUrl = "/account/personalinformation"
});
}
如果您不需要访问匿名类型的成员(例如list[0].transKey
)或者使用反射是可以的,那么Alex的回答可能更适合您的问题。