在 VB .NET 中在运行时构造动态属性
有没有办法在 VB .NET 中使用内省在运行时动态创建属性?
例如,假设我有一个类,
Public Class Foo
Public Property Bar() As String
get
...
end get
set(ByVal value As String)
...
end set
End Class
有没有办法在运行时创建属性 Bar?
谢谢!
Is there a way to dynamically create properties at runtime in VB .NET using introspection?
e.g. Suppose I had a class
Public Class Foo
Public Property Bar() As String
get
...
end get
set(ByVal value As String)
...
end set
End Class
Is there a way to create property Bar at runtime?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案是 Reflection.Emit< /a>.编码没有太多乐趣,但可以做你想做的事。
The answer is Reflection.Emit. Not a lot of fun to code, but does what you want.
如果您只需要动态变量列表,则始终可以将字典对象设置为类的成员,然后使用方法设置或获取特定的字典项。
If you just want a dynamic list of variables, you can always set up a dictionary object as a member of your class, and then set or get a particular dictionary item with a method.
进一步添加我的评论,您可以向您的类添加一个索引器 - 它可以让您获取/设置成员变量。
编辑:对不起。我不知道 vb.net 没有索引器。
但人们仍然可以使用支持字典编写代码,它可以像索引器一样工作
Adding further to my comment, you can add an indexer to your class - which can let you get/set member variable.
EDIT: I am sorry. I didn't know that vb.net doesn't have indexers.
But one can still write code with backing dictionary, which can work like an indexer
不幸的是,没有办法在运行时改变类的结构。元数据在编译时是固定的,并且在运行时运行不变。
对于吹毛求疵的人来说:)
这并不是100%正确的。分析和 ENC API 允许您在运行时更改元数据的结构。但两者都不适用于这种情况。
Unfortunately there is no way to do alter the structure of a class an runtime. Metadata is fixed at compile time and runs unaltered at runtime.
For the Nitpickers :)
This is not 100% true. The profiling and ENC APIs allow you to change the structure of metadata at runtime. But neither are really applicable for this scenario.