【发布时间】:2019-06-30 18:15:21
【问题描述】:
我在 .Net 上使用 winform 工作,它使用 System.Reflection 根据模型类自动生成控件,如下所示:
Imports System.Reflection
Public Class DynamicForm(Of Model As {IModelBase, Class, New})
Protected Sub InitializeComponent()
'A lot of not relevant code here...
For Each prop As PropertyInfo In GetType(Model).GetProperties
If Not HasControl(prop) Then Continue For
Dim control = CreateControl(prop)
Dim label = CreateLabel(prop)
SetLocation(label, control)
Me.Controls.Add(control)
Me.Controls.Add(label)
ResizeWindow(control.Height)
Next
End Sub
End Class
当然,模型可以有很多我不想被用户直接编辑的属性,所以我采用使用属性来标记你想要显示的属性的解决方案,如下所示:
Public Class HasControl
Inherits Attribute
Public Property Label As String
Public Sub New(label As String)
Me.Label = label
End Sub
End Class
然后我的模型看起来像:
Public Class Clients
Implements IModelBase
<HasControl("First name:")>
Public Property FirstName As String
Public Property CreatedTime As Date
End Class
现在,我使用 IModelBase 接口只是为了确保在此窗口中不能使用任何类,但我最近开始使用其他东西。我的许多模型都像客户、工人、卖家、用户等。这些模型有许多相似的属性,所以我用这些属性创建了一个接口:
Public Interface IHumanData
Inherits IModelBase
<HasControl("First name:")>
Public Property FirstName As String
<HasControl("Last name:")>
Public Property LastName As String
End Interface
Public Class Seller
Implements IHumanData
Public Property FirstName As String Implements IHumanData.FirstName
Public Property LastName As String Implements IHumanData.LastName
End Class
这个问题是“HasControl”属性没有分配给我的卖家属性。我知道如果我使用继承而不是接口实现,这实际上是可行的,但是当我想创建这样的东西时,继承有一个限制:
Public Class Worker
Implements IHumanData, IDateStorageData, ILocationData, ISortOfRandomData
' A bunch of properties auto generated by VisualStudio
End Class
那么,实际上有一种简单的方法可以通过接口实现传递属性吗?
【问题讨论】:
标签: .net vb.net generics interface attributes