gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:51:16 27 4
gpt4 key购买 nike

我有一个类:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com