且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 C# 中向类动态添加字段

更新时间:2023-12-06 11:02:46

您不能在运行时更改类定义.但是,您可以创建一个继承自原始类的新类(如果它不是 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.