2013-06-04 116 views
3

我知道在c#4或4.5中可以创建匿名类型和动态类型,但我不确定它是如何工作的。 我遍历一个SharePoint站点集合,我想为每个子站点添加一个项目到列表,其中有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(); 
} 

回答

2

您可以通过在你的new声明中没有给予特定类型的创建匿名类型:

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

这是可行的,但你将无法使用属性,如opportunityInfo[0].col1,因为你”我已明确声明该列表为List<object>。如果您将其声明为List<dynamic>,您将可以访问匿名课程的成员。

(注:我不知道数据绑定副手如何将匿名类型的工作,或List的类型是否会做出任何行为差异)

+0

之后,我可以在gridview中使用boundColumn? –

+0

正如我所说,我不确定。你必须自己尝试一下! –

+0

它表示类型预计在第一个左括号 –

1

Anonymouse没有名字。

只需创建一个没有名称的新类,它将成为您的anonymouse对象。

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

这不会编译。生成匿名对象时,您不会在'new'之后包含parens。当你包含它们时,编译器希望你也提供一个类型。 –

+0

这只是拼写错误。 – JSJ