我是一个vb.net新手,所以请多多包涵。是否可以在 Visual Basic 中为类创建属性(或属性)(我使用的是 Visual Basic 2005)?所有关于元编程的网络搜索都没有结果。这是一个例子来阐明我的意思。
public class GenericProps
public sub new()
' ???
end sub
public sub addProp(byval propname as string)
' ???
end sub
end class
sub main()
dim gp as GenericProps = New GenericProps()
gp.addProp("foo")
gp.foo = "Bar" ' we can assume the type of the property as string for now
console.writeln("New property = " & gp.foo)
end sub
那么可以定义函数addProp吗?
谢谢! 阿米特
最佳答案
不可能在运行时使用新属性修改类1。 VB.Net 是一种静态语言,因为它无法在运行时修改其定义的类。您可以使用属性包来模拟您正在寻找的内容。
Class Foo
Private _map as New Dictionary(Of String, Object)
Public Sub AddProperty(name as String, value as Object)
_map(name) = value
End Sub
Public Function GetProperty(name as String) as Object
return _map(name)
End Function
End Class
它不允许以 myFoo.Bar 的形式直接访问,但您可以调用 myFoo.GetProperty("Bar")。
1 我相信分析 API 可能可以实现这一点,但这可能不是您想要的。
关于vb.net - Visual Basic 中类的动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/593049/