簡體   English   中英

創建后將屬性添加到匿名類型

[英]Add property to anonymous type after creation

我使用匿名對象將我的Html屬性傳遞給一些輔助方法。 如果消費者沒有添加ID屬性,我想在我的幫助方法中添加它。

如何向此匿名對象添加屬性?

以下擴展類將為您提供所需的內容。

public static class ObjectExtensions
{
    public static IDictionary<string, object> AddProperty(this object obj, string name, object value)
    {
        var dictionary = obj.ToDictionary();
        dictionary.Add(name, value);
        return dictionary;
    }

    // helper
    public static IDictionary<string, object> ToDictionary(this object obj)
    {
        IDictionary<string, object> result = new Dictionary<string, object>();
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);
        foreach (PropertyDescriptor property in properties){
            result.Add(property.Name, property.GetValue(obj));
        }
        return result;
    }
}

我假設你的意思是匿名類型,例如new { Name1=value1, Name2=value2}等。如果是這樣,你就不幸了 - 匿名類型是正常類型,因為它們是固定的,編譯代碼。 它們恰好是自動生成的。

可以做的是寫new { old.Name1, old.Name2, ID=myId }但我不知道這是不是你想要的。 有關情況的更多細節(包括代碼示例)將是理想的。

或者,您可以創建一個始終具有ID的容器對象,以及包含其余屬性的任何其他對象。

如果您嘗試擴展此方法:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);

雖然我確信Khaja的Object擴展可以工作,但是通過創建RouteValueDictionary並傳入routeValues對象,從Context中添加其他參數,然后使用帶有RouteValueDictionary而不是對象的ActionLink重載返回,可能會獲得更好的性能:

這應該做的伎倆:

    public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)
    {
        RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);

        // Add more parameters
        foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
        {
            routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);
        }

        return helper.ActionLink(linkText, actionName, routeValueDictionary);
    }
public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}

這將接受文本框應具有的id值,標簽應該引用。 如果消費者現在不在textBoxHtmlAttributes中包含“id”屬性,則該方法將創建不正確的標簽。

如果在labelHtmlAttributes對象中添加了此屬性,我可以通過反射檢查。 如果是這樣,我想添加它或創建一個添加它的新匿名對象。 但是因為我不能通過遍歷舊屬性並添加我自己的“id”屬性來創建一個新的匿名類型,所以我有點卡住了。

具有強類型ID屬性然后是匿名類型“屬性”屬性的容器將需要不重寫“添加id字段”要求的代碼重寫。

希望這種反應是可以理解的。 這是一天的結束,不能讓我的大腦排成一行..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM