Python has a setattr
to set public attributes for any class on the fly.
So, how to do t开发者_运维百科hat with VB.net ?
I mean :
Public Class abc
...
End Class
' Set it as :
abc.setattr("prop", 5)
' Use it as :
Dim ob As New abc
value = abc.prop
Is that possible with VB.net - If yes, Please explain how ?
There is no such feature in VB.NET. You have to define Properties manually.
For instance - Anonymous types.
Dim obj = New With {.No = 10, .Name = ""}
obj.Name = "Mr.X"
Or
Named types
Public Class Abc
Public Property No As Integer
Public Property Name As String
End Class
You can do this by using the DLR and Dynamic objects like AVD showed.
However something like impromptu-interface will make this eassier for you. Here is a blog about it.
Dim c As Object = Builder.[New]()
Dim abc = c.abc(New With {.prop = 5})
or
Dim c As Object = Builder.[New]()
Dim abc = c.abc
abc.("prop") = 5
Which is close to what you desired.
精彩评论