C# 在对象中强制转换匿名类型并检索一个字段
我使用C#asp.net4 我有一种用匿名类型(字段:Title,CategoryId)填充转发器的方法,在转发器内部我还放置了一个标签:C# 在对象中强制转换匿名类型并检索一个字段,c#,asp.net,repeater,anonymous-types,C#,Asp.net,Repeater,Anonymous Types,我使用C#asp.net4 我有一种用匿名类型(字段:Title,CategoryId)填充转发器的方法,在转发器内部我还放置了一个标签: var parentCategories = from c in context.CmsCategories where c.CategoryNodeLevel == 1 select new { c.Title, c.
var parentCategories = from c in context.CmsCategories
where c.CategoryNodeLevel == 1
select new { c.Title, c.CategoryId };
uxRepeter.DataSource = parentCategories;
uxRepeter.DataBind();
我需要在Repeater Event ItemDataBound上更改Repeater内每个标签的文本属性
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(匿名类型字段标题)并将其设置为标签的文本适当性
我知道匿名类型只能转换为对象类型,但在我的例子中,我的匿名类型有Title和CategoryId字段
我的问题:
如何在我感兴趣的情况下施放和检索字段?谢谢你在这方面花时间
编辑:
我收到一些错误:
Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.Int32]' to type 'System.String'.
无法将类型为“f_uuAnonymousType0`2[System.String,System.Int32]”的对象强制转换为类型为“System.String”。
您不能将匿名类型强制转换为任何类型,因为您实际上没有可以将其强制转换为的类型,正如您基本上已经指出的那样
所以你真的有两个选择
var parentCategories = from c in context.CmsCategories
where c.CategoryNodeLevel == 1
select new RepeaterViewModel { c.Title, c.CategoryId };
示例2:(我还认为您是要分配链接变量的最后一行)
在这种情况下,可以使用
动态
。我认为代码应该是:
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.
}
约瑟夫提出的选择是好的,但有一种可怕的方式可以做到这一点。它有点脆弱,因为它依赖于您在两个地方以完全相同的方式指定匿名类型。我们开始:
public static T CastByExample<T>(object input, T example)
{
return (T) input;
}
编辑:进一步折皱-两个匿名类型创建表达式必须位于同一程序集(项目)中。很抱歉,我之前忘了提到这一点。你难道不能强制转换到
(typeof(new{Title=”“,CategoryID=0}))
?我一直在想,这仅仅是一个实现细节吗,相同形状的两个匿名类型是类型兼容的,或者它们必须兼容是规范的一部分?@Rex:这是规范的一部分。我没有引用,但基本上在同一个程序集中,两个具有相同属性名和相同顺序类型的匿名类型构造表达式必须引用相同的类型。@Rex:第7.6.10.6节:“在同一个程序中,两个匿名对象初始值设定项以相同的顺序指定相同名称和编译时类型的属性序列,将生成相同匿名类型的实例。”(Jon在没有引用的情况下,逐字引用了dern的话!)谢谢Joesph的回复。你的例子2而不是Ex 1有什么缺点吗?谢谢你的时间this@GibboK你失去了强类型,因此任何接触事件处理程序的开发人员都必须知道可以在该对象上访问什么ur事件处理程序是将e.Item强制转换到的类。编译时已知的所有其他事件。
public static T CastByExample<T>(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;