C#: How to add an attributes to an object at run-time?(C#:如何在运行时向对象添加属性?)
问题描述
作为一个实体类,我想在运行时添加一个属性,应该怎么做?
As an entity class, I want to add an attributes at run-time, how should I do?
推荐答案
需要看什么属性?如果是数据绑定等,TypeDescriptor 应该可以工作:
What needs to see the attributes? If it is things like data-binding etc, TypeDescriptor should work:
TypeDescriptor.AddAttributes(type, attribs);
TypeDescriptor.AddAttributes(instance, attribs);
这只会影响 System.ComponentModel 的使用(不是直接反射),但这通常就足够了 - 例如,您可以通过上述关联一个 TypeConverter.
This only affects System.ComponentModel usage (not direct reflection), but that is often enough - for example, you can associate a TypeConverter via the above.
如果您所说的属性"是指属性",那么(再次,就数据绑定而言)TypeDescriptor 也有潜力 - 但它并不重要;您需要在对象上实现 ICustomTypeDescriptor,或者为该类型编写 CustomTypeDescriptor - 无论哪种情况,您都需要编写自己的 PropertyDescriptor代码> 实现(通常与每个实例的字典等对话).这将被任何使用的东西使用:
If by "attributes" you mean "properties", then (again, as far as data-binding is concerned) TypeDescriptor also has potential there - but it is non-trivial; you need to either implement ICustomTypeDescriptor on the object, or to write a CustomTypeDescriptor for the type - and in either case, you need to write your own PropertyDescriptor implementation (often talking to a per-instance dictionary etc). This will get used by anything that uses:
// only works if you use TypeDescriptionProvider
PropertyDescriptorCollection typeProps = TypeDescriptor.GetProperties(type);
// works via TypeDescriptionProvider or ICustomTypeDescriptor
PropertyDescriptorCollection objProps = TypeDescriptor.GetProperties(obj);
同样,这涵盖了广泛的数据绑定和类似场景.例如,见这里 -然而,这远非微不足道.示例用法(来自链接)在运行时添加了两个属性:
Again, this covers a wide range of data-binding and similar scenarios. For an example of this, see here - it is far from trivial, however. The example usage (from the link) adds two properties at runtime:
Bag.AddProperty<int>("TestProp", new DefaultValueAttribute(5));
Bag.AddProperty<string>("Name");
这篇关于C#:如何在运行时向对象添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:如何在运行时向对象添加属性?
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
