gpt4 book ai didi

c# - 如何创建匿名对象列表

转载 作者:行者123 更新时间:2023-11-30 16:17:37 25 4
gpt4 key购买 nike

我知道在 c# 4 或 4.5 中你可以创建匿名类型和动态类型,但我不确定它是如何工作的。我正在遍历一个共享点网站集,我想为每个子网站添加一个项目到列表中,有 3 列

但是我不想为此创建一个类,因为它只特定于此方法。

private void RenderGrid()
{
string currentUrl = SPContext.Current.Site.Url;
List<object> listobject= new List<object>();

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite clientSiteCollection = new SPSite(currentUrl))
{
foreach (SPWeb web in clientSiteCollection.AllWebs)
{
string webtemplate = web.Properties["WebTemplate"];

if (webtemplate.Equals("xx"))
{
SPList xx = web.Lists.TryGetList(Constants.Lists.xx);

if (opportunityInfoList != null)
{
opportunityInfo.Add(new object() {
col1 = "value1",
col2 = "value2",
col3 = "value3"
});
}
}
}
}
});

lastCreatedOpportunitiesGrid.DataSource = opportunityInfo;
lastCreatedOpportunitiesGrid.DataBind();
}

最佳答案

您可以通过在 new 中不提供特定类型来创建匿名类型声明:

opportunityInfo.Add(new {
col1="value1",
col2="value2",
col3= "value3"});

这会起作用,但您将无法使用像 opportunityInfo[0].col1 这样的属性因为您已将该列表明确声明为 List<object> .如果您改为将其声明为 List<dynamic>您将能够访问匿名类的成员。

(注意:我不确定数据绑定(bind)如何与匿名类型一起工作,或者 List 的类型是否会产生任何行为差异。)

关于c# - 如何创建匿名对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16918590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com