添加属性创建后匿名类型 [英] Add property to anonymous type after creation
本文介绍了添加属性创建后匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用匿名对象来传递我的HTML属性的一些辅助方法。
如果消费者没有添加ID属性,我想将其添加到我的helper方法。
I use an anonymous object to pass my Html Attributes to some helper methods. If the consumer didn't add an ID attribute, I want to add it in my helper method.
我如何将属性添加到该匿名对象?
How can I add an attribute to this anonymous object?
推荐答案
下面的扩展类会得到你所需要的。
The following extension class would get you what you need.
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;
}
}
这篇关于添加属性创建后匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文