创建后将属性添加到匿名类型

Bor*_*ens 99 c# reflection anonymous-objects

我使用匿名对象将我的Html属性传递给一些辅助方法.如果消费者没有添加ID属性,我想在我的帮助方法中添加它.

如何向此匿名对象添加属性?

Kha*_*din 77

以下扩展类将为您提供所需的内容.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.anonymousobjecttohtmlattributes(v=vs.108).aspx做同样的事情,但它内置于System.Web.Mvc.HtmlHelper . (11认同)
  • 100%正确.即使你通常使用Html属性的匿名类型,它实际上是一个IDictionary <string,object>,因此你可以轻松地添加/删除它. (3认同)

Jon*_*eet 47

我假设你的意思是匿名类型,例如new { Name1=value1, Name2=value2}等等.如果是这样,你运气不好 - 匿名类型是正常类型,因为它们是固定的,编译代码.它们恰好是自动生成的.

可以做的是写new { old.Name1, old.Name2, ID=myId },但我不知道这是否是你想要的真的是.有关情况的更多细节(包括代码示例)将是理想的.

或者,您可以创建一个始终具有ID 的容器对象,以及包含其余属性的任何其他对象.


Lev*_*kon 15

如果您尝试扩展此方法:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
Run Code Online (Sandbox Code Playgroud)

虽然我确信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);
    }
Run Code Online (Sandbox Code Playgroud)