我无法让这个工作!我希望能够在从继承自system.dynamic.dynamicobject的基类继承的派生类上创建动态属性吗?
我创建了一个VB.net抽象类,我希望从继承自此抽象类的实例上继承动态属性。基类读取XML文档并将元素和任何属性转换为属性列表Dictionary。
这个想法是,当派生类被实例化时,抽象类propertyList中列出的所有项都作为公共属性公开。从下面列出的代码中,如果将属性id添加到属性列表中,那么我希望能够提供Feed.id
抽象类看起来像这样:
Public MustInherit Class ItemClass
Inherits DynamicObject
Protected Shared propertyList As New Dictionary(Of String, String)
Protected Shared p_client As Phm.Adfero.Client
Protected Shared p_id As Integer
Protected Shared p_uri As Phm.Adfero.Uri
Protected Shared p_data As Phm.Adfero.Data
Protected Shared p_paramList As New Dictionary(Of String, String)
Sub New(ByRef client As Client, ByVal id As Integer)
Dim instance As New Instance(Me)
Dim instanceName = instance.getInstanceName()
instance = Nothing
If Not IsNothing(client) Then
p_client = client
Else
Throw New ArgumentException("Object Parameter client is required!")
End If
If Not IsNothing(id) Then
p_id = id
Else
Throw New ArgumentException("Integer Parameter id is required!")
End If
p_paramList.Add("identifier", instanceName & "s/" & p_id.ToString)
p_uri = New Phm.Adfero.Uri(client, p_paramList)
p_data = New Phm.Adfero.Data(client, p_uri)
End Sub
Protected Shared Sub transposeXML()
Dim rootElement As String = p_data.Xml.DocumentElement.Name
For Each baseElement As XmlNode In p_data.Xml.SelectSingleNode(rootElement)
For Each element As XmlNode In baseElement
If element.Name <> "fields" Then
propertyList.Add(element.Name, element.InnerText)
Else
For Each field As XmlNode In baseElement.SelectSingleNode(element.Name).ChildNodes
For Each attrib As XmlAttribute In field.Attributes
propertyList.Add(attrib.Value, field.InnerText)
Next
Next
End If
Next
Next
End Sub
Public Overrides Function TryGetMember(ByVal binder As GetMemberBinder, _
ByRef result As Object) As Boolean
Dim name As String = binder.Name.ToLower()
Return propertyList.TryGetValue(name, result)
End Function
Public Overrides Function TrySetMember(binder As SetMemberBinder, value As Object) As Boolean
propertyList(binder.Name.ToLower()) = value
Return True
End Function
End Class
继承上述类的派生类的示例如下:
Public Class Feed
Inherits ItemClass
Sub New(ByRef client As Client, ByRef id As Integer)
MyBase.New(client, id)
End Sub
Public Overrides Function TryGetMember(binder As GetMemberBinder, ByRef result As Object) As Boolean
Dim res As Object = Nothing
Dim retVal As Boolean = MyBase.TryGetMember(binder, res)
result = res
Return retVal
End Function
Public Overrides Function TrySetMember(binder As System.Dynamic.SetMemberBinder, value As Object) As Boolean
Return MyBase.TrySetMember(binder, value)
End Function
End Class
感谢您提前提供任何帮助。