【发布时间】:2010-09-19 00:32:14
【问题描述】:
我使用匿名对象将我的 Html 属性传递给一些辅助方法。 如果消费者没有添加 ID 属性,我想在我的辅助方法中添加它。
如何向这个匿名对象添加属性?
【问题讨论】:
标签: c# reflection anonymous-objects
我使用匿名对象将我的 Html 属性传递给一些辅助方法。 如果消费者没有添加 ID 属性,我想在我的辅助方法中添加它。
如何向这个匿名对象添加属性?
【问题讨论】:
标签: c# reflection anonymous-objects
我假设您的意思是匿名类型,例如new { Name1=value1, Name2=value2} 等等。如果是这样,那你就不走运了——匿名类型是普通类型,因为它们是固定的编译代码。它们恰好是自动生成的。
你可以做的是写new { old.Name1, old.Name2, ID=myId },但我不知道这是否真的是你想要的。一些关于这种情况的更多细节(包括代码示例)将是理想的。
或者,您可以创建一个容器对象,该对象总是有一个 ID,而其他任何对象都包含其余属性。
【讨论】:
public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}
这将接受文本框应具有的 id 值和标签应引用的值。 如果消费者现在没有在 textBoxHtmlAttributes 中包含“id”属性,则该方法将创建一个不正确的标签。
我可以通过反射检查是否在 labelHtmlAttributes 对象中添加了此属性。如果是这样,我想添加它或创建一个新的匿名对象来添加它。 但是因为我无法通过遍历旧属性并添加自己的“id”属性来创建新的匿名类型,所以我有点卡住了。
具有强类型 ID 属性和匿名类型“属性”属性的容器将需要不符合“添加 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;
}
}
【讨论】:
如果您尝试扩展此方法:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
虽然我确信 Khaja 的对象扩展会起作用,但您可能会通过创建 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);
}
【讨论】: