如何在 C# 中向类动态添加字段 [英] How can I dynamically add a field to a class in C#

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

问题描述

有什么方法可以在运行时将 Field(或 FieldInfo,也许是一样的)添加到类中?

Is there any way to add Field (or FieldInfo, maybe this is the same) to a class at runtime?

推荐答案

您不能在运行时更改类定义.但是,您可以创建一个继承自原始类的新类(如果它不是 sealed)并声明该字段.您可以通过使用 System.Reflection.Emit 发出适当的 IL 代码来实现这一点.

You can't alter a class definition at runtime. However, you can create a new class that inherits from the original class (if it's not sealed) and declares the field. You can do this by emitting the appropriate IL code using System.Reflection.Emit.

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

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