听起来您可能正在寻找一种在一定程度上确定您的类型的方法。一种方法可能是使用自定义属性,该属性使用反射很容易找到和过滤。
Public Class RealMcCoy
Inherits Attribute
Public Property IsReal As Boolean
Public Sub New(b as Boolean)
IsReal = b
End Sub
End Class
<RealMcCoy(True)>
Public Class Patient
...
End Class
<RealMcCoy(True)>
Public Class Appointment
...
End Class
现在在迭代属性时,检查它是否是 RealMcCoy 以查看它是否是您想要/需要钻取的。由于 Attribute 将在 Type 上,因此有一个额外的步骤来获取每个属性的 Type 并轮询 that
Dim props As PropertyInfo() = myFoo.GetType.GetProperties
Dim pt As Type
For Each pi As PropertyInfo In props
pt = pi.PropertyType ' get the property type
Dim attr() As RealMcCoy =
DirectCast(pt.GetCustomAttributes(GetType(RealMcCoy), True), RealMcCoy())
If attr.Length > 0 Then
' bingo, baby...optional extra test:
If attr(0).IsReal Then
Console.Beep()
End If
Else
' skip this prop - its not a real mccoy
End If
Next
End Sub
如果您添加一个类型而不添加属性,它会中断,但它比必须更新每个类型的组成属性更容易中断。伪造的接口会更容易查询,但也有同样的缺点。
我不确定我是否理解“游戏”事物的问题 - 你是否害怕其他类型会被选中?属性将很难“游戏”,因为它们被编译到程序集中,但以上内容仍可用于返回 GUID(可能附加到程序集?)而不是 bool 以提供一些保证。
很难获得绝对的确定性。
RealMcCoy 属性可能不会应用于您的顶级类型 (PatientAppointment),而只会应用于将用作其他类型的属性的类型(类)。对象是一种轻松识别这些的方法。
根据其使用方式,已经标识为 RealMcCoys 的 TypeName-PropertyName 对的字典或哈希表可能很有用,因此可以缩短整个反射过程。而不是即时添加,您可能可以将整个列表预先构建为shown in this answer - 请参阅RangeManager.BuildPropMap 过程。
我不太确定继承方法,因为您可能希望在某处实际使用继承。接口可能会更好地工作:最初,它的存在可能是一开始的触发器,但也可以用来提供服务。
简单的测试用例:
' B and C classes are not tagged
Friend Class FooBar
Public Property Prop1 As PropA
Public Property Prop2 As PropB
Public Property Prop3 As PropC
Public Property Prop4 As PropD
Public Property Prop5 As PropE
End Class
在 for 循环中添加一行:
Dim f As New FooBar
' use instance:
Dim props As PropertyInfo() = f.GetType.GetProperties
Dim pt As Type
For Each pi As PropertyInfo In props
pt = pi.PropertyType
Dim attr() As RealMcCoy =
DirectCast(pt.GetCustomAttributes(GetType(RealMcCoy), True), RealMcCoy())
Console.WriteLine("Prop Name: {0}, prop type: {1}, IsRealMcCoy? {2}",
pi.Name, pt.Name, If(attr.Length > 0, "YES!", "no"))
Next
输出:
Prop Name: Prop1 prop type: PropA IsRealMcCoy? YES!
Prop Name: Prop2 prop type: PropB IsRealMcCoy? no
Prop Name: Prop3 prop type: PropC IsRealMcCoy? no
Prop Name: Prop4 prop type: PropD IsRealMcCoy? YES!
Prop Name: Prop5 prop type: PropE IsRealMcCoy? YES!