Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

c# - Cast an Anonymous Types in Object and retrieve one Field

I use C# asp.net4.

I have a method to populate a Repeater with Anonymous Types (Fields: Title, CategoryId), inside the Repeater I also placed a Label:

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

I need to change Text Properties for each label inside my Repeater on Repeater Event ItemDataBound

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

So I need set the properties for Label.Text using e.Item (or a better way if any).

My problem I'm not able to CAST the e.Item (Anonymous type Field Title) and set it as Text Propriety for my Label.

I understand Anonymous Type can be casted to only Object Type, but in my case my Anonymous Type has Title and CategoryId Fields.

My question:

How to cast and retrieve the field with I'm interested? Thanks for your time on this?

EDIT: SOME ERROR I RECEIVE:

Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.Int32]' to type 'System.String'.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The options Joseph presents are good ones, but there is a horrible way you can do this. It's somewhat fragile, as it relies on you specifying the anonymous type in exactly the same way in two places. Here we go:

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

Then:

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;

EDIT: Further wrinkle - the two anonymous type creation expressions have to be in the same assembly (project). Sorry for forgetting to mention that before now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...