在Object中转换匿名类型并检索一个Field

我使用C#asp.net4。

我有一个方法来填充带有匿名类型的Repeater(Fields:Title,CategoryId),在Repeater中我还放置了一个Label:

var parentCategories = from c in context.CmsCategories where c.CategoryNodeLevel == 1 select new { c.Title, c.CategoryId }; uxRepeter.DataSource = parentCategories; uxRepeter.DataBind(); 

我需要在Repeater事件ItemDataBound上更改Repeater中的每个标签的Text Properties

  protected void uxRepeter_ItemDataBound(object sender, RepeaterItemEventArgs e) { HyperLink link = (HyperLink)e.Item.FindControl("uxLabel"); uxLabel.Text = // How to do here!!!!!!!! } 

所以我需要使用e.Item设置Label.Text的属性(或者更好的方法)。

我的问题我无法使用e.Item(匿名类型字段标题)并将其设置为我的标签的Text Propriety。

我理解匿名类型只能被转换为对象类型,但在我的情况下,我的匿名类型有标题和CategoryId字段。

我的问题:

如何投射和检索我感兴趣的领域? 谢谢你的时间吗?

编辑:我收到的一些错误:

 Unable to cast object of type 'f__AnonymousType0`2[System.String,System.Int32]' to type 'System.String'. 

约瑟夫提出的选择很好,但你可以做到这一点。 它有点脆弱,因为它依赖于你在两个地方以完全相同的方式指定匿名类型。 开始了:

 public static T CastByExample(object input, T example) { return (T) input; } 

然后:

 object item = ...; // However you get the value from the control // Specify the "example" using the same property names, types and order // as elsewhere. var cast = CastByExample(item, new { Title = default(string), CategoryId = default(int) } ); var result = cast.Title; 

编辑:进一步皱纹 – 两个匿名类型创建表达式必须在同一个程序集(项目)中。 很抱歉忘记在此之前提及。

你不能将匿名类型转换为任何东西,因为你实际上没有任何类型可以将其强制转换,正如你已经基本指出的那样。

所以你真的有两个选择。

  1. 不要转换为匿名类型,而是为了处理此场景而构建的已知类型
  2. 为项目分配动态变量并使用动态属性

例1:

 var parentCategories = from c in context.CmsCategories where c.CategoryNodeLevel == 1 select new RepeaterViewModel { c.Title, c.CategoryId }; 

示例2 :(我认为你是最后一行,你打算分配链接var)

 protected void uxRepeter_ItemDataBound(object sender, RepeaterItemEventArgs e) { HyperLink link = (HyperLink)e.Item.FindControl("uxLabel"); dynamic iCanUseTitleHere = e.Item; link.Text = iCanUseTitleHere.Title; //no compilation issue here } 

在这种情况下,您可以使用dynamic 。 我认为代码将是:

 protected void uxRepeter_ItemDataBound(object sender, RepeaterItemEventArgs e) { dynamic link = (dynamic)e.Item.FindControl("uxLabel"); uxLabel.Text = link.Title; //since 'link' is a dynamic now, the compiler won't check for the Title property's existence, until runtime. } 

你不能只是转换为(typeof(new { Title = "", CategoryID = 0 }))