如何在 C# 中在运行时向类添加属性? [英] How Can I add properties to a class on runtime in C#?

查看:141
本文介绍了如何在 C# 中在运行时向类添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课:

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

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

Is it possible to add properties / fields to this class on run-time ?

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

伪示例:

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

我已经阅读了这个问题 但它使用接口

I already read this question but it uses interface

提前致谢.

推荐答案

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

You cannot extend an existing class with new members at runtime. However, you can create a new class using System.Reflection.Emit that has the existing class as base class.

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

请参阅 TypeBuilder.DefineProperty 方法(字符串、PropertyAttributes、Type、Type[])一个完整的例子.

See TypeBuilder.DefineProperty Method (String, PropertyAttributes, Type, Type[]) for a full example.

这篇关于如何在 C# 中在运行时向类添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆