Cast an Anonymous Types in Object and retrieve one Field

前端 未结 4 1716
闹比i
闹比i 2020-12-03 23:18

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:



        
相关标签:
4条回答
  • You can't cast the anonymous type to anything because you literally have no type to cast it to, as you've basically pointed out already.

    So you really have two options.

    1. Don't cast to an anonymous type, but rather a known type that you build just for handling this scenario or
    2. assign a dynamic variable to the item and use dynamic properties instead

    Example 1:

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

    Example 2: (also I think you're last line you meant to assign the link 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
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 00:13

    You can use a dynamic in this case. I think the code would be:

    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.
    }
    
    0 讨论(0)
  • 2020-12-04 00:20

    Can't you just cast to (typeof(new { Title = "", CategoryID = 0 }))?

    0 讨论(0)
提交回复
热议问题