在 C# 中生成运行时代码(结构、类)
我需要在 C#(可能在 CLI 中)托管环境中运行时生成结构和类。 假设我拥有与某个类/结构的这些数据成员关联的所有数据和数据类型。现在我需要在运行时生成结构/类,之后我需要在这些运行时创建的结构字段内映射数据。
我已从 XML 文件(即 BSTR field1、BSTR field2、BSTR field3、BSTR field4、BSTR field5、long field6)读取数据。
现在我需要在运行时创建一个结构体,其中 sizeof
是所有字段(我在上面列出的)的总和,然后我可以轻松地一一访问这些字段,从而形成整个完整的结构体。
我该如何解决这个问题?
问候,
乌斯曼
I need to generate structs and classes at run time in C# (might be in CLI) managed environment.
Suppose I have all data and data types associated with those data memebers of some class/struct. Now I need to generate structs/classes at runtime, and after that I need to map data inside those runtime created struct fields.
I have read data from an XML file (i.e. BSTR field1, BSTR field2, BSTR field3, BSTR field4, BSTR field5, long field6).
Now I need to create a struct at runtime which has sizeof
the sum of all fields (which I listed above) and then I can easily access those fields one by one, so that whole completed struct is formed.
How can I solve this problem?
Regards,
Usman
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要检查 CodeDom 和 Reflection.Emit。
You need to check CodeDom and Reflection.Emit.
动态生成的类型对象可能对您的场景有所帮助。弗拉基米尔·博杜罗夫 (Vladimir Bodurov) 已编写关于它,包括源代码(如果它更小,我会在这里发布)。
Dynamically generated typed object may help in your scenario. Vladimir Bodurov has written about it including source code (which I would post here if it was smaller).
System.Reflection.Emit
拥有实现这一目标所需的所有工具。从TypeBuilder
。System.Reflection.Emit
has all the tools you need to make that happen. Start withTypeBuilder
.