添加属性创建后匿名类型

编程入门 行业动态 更新时间:2024-10-16 00:23:33
本文介绍了添加属性创建后匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

添加属性创建后匿名类型

本文发布于:2023-11-07 00:41:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565086.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!