c# - 如何在 C# 中的运行时向类添加属性?

标签 c# .net reflection .net-4.0 properties

我有一个类:

class MyClass 
{
}
...
MyClass c = new MyClass();

是否可以在运行时向此类添加属性/字段?

(我不知道它们在编译时的类型或名称是什么,而且它们没有我可以使用的通用接口(interface)。)

伪例子:

 Add property named "Prop1" [type System.Int32]
 Add property named "Prop900" [type System.String]

我已经阅读了 this question但它使用接口(interface)

提前致谢。

最佳答案

您不能在运行时使用新成员扩展现有类。但是,您可以使用 System.Reflection.Emit 创建一个新类以现有类作为基类。

typeBuilder.SetParent(typeof(MyClass));
typeBuilder.DefineProperty("Prop1", ..., typeof(System.Int32), null);
...

参见 TypeBuilder.DefineProperty Method (String, PropertyAttributes, Type, Type[])一个完整的例子。

关于c# - 如何在 C# 中的运行时向类添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14724822/

相关文章:

c# - Performance Monitor .NET CLR Networking 4.0.0.0 实例命名

.Net 停止监听套接字

java - 如何在没有引用的情况下找到类的单例对象?

java - 使用运行时给定的类型创建通用映射

.net - LINQ to SQL 还是经典的 ADO.NET?

c# - 获取给定类型的编程语言

c# - 当另一个类更新时更新 ListView

c# - 强制 INotifyDataErrorInfo 验证

c# - 在新行中打印字符串 (C#)

c# - AngleSharp Html Parser 线程安全吗?