gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:36:06 25 4
gpt4 key购买 nike

我使用匿名对象将我的 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;
}
}

关于c# - 创建后将属性添加到匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/233711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com