gpt4 book ai didi

c# - 在对象中转换匿名类型并检索一个字段

转载 作者:太空狗 更新时间:2023-10-29 22:08:30 25 4
gpt4 key购买 nike

我使用 C# asp.net4。

我有一种方法可以使用匿名类型(字段:Title、CategoryId)填充 Repeater,在 Repeater 中我还放置了一个标签:

        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 内每个标签的文本属性

   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(匿名类型字段标题)并将其设置为我的标签的文本属性。

我知道匿名类型只能转换为对象类型,但在我的例子中,我的匿名类型有标题和类别 ID 字段。

我的问题:

如何转换和检索我感兴趣的字段?感谢您抽出宝贵的时间?

编辑:我收到一些错误:

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

最佳答案

Joseph 提供的选项是不错的选项,但是您可以采用一种糟糕的方式来执行此操作。它有点脆弱,因为它依赖于您在两个地方以相同的方式完全 指定匿名类型。我们开始吧:

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;

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

关于c# - 在对象中转换匿名类型并检索一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6901506/

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