在我的 ASP.Net MVC 页面中,我可以单击列标题以按该列排序,但这涉及 aspx 中的“魔术字符串”,这可能会导致运行时问题。我试图在运行时检查传递给排序依据的值是否有效。我有一个基类,我的所有实体都继承自:
Public MustInherit Class BaseEntity(Of T)
'Some Property and method definitions...'
Public Shared Function IsValidSearchProperty(name As String) As Boolean
Dim rootPart As String = name
Dim nested As Boolean = False
If rootPart.Contains(".") Then
rootPart = rootPart.Split("."c)(0)
nested = True
End If
Dim properties As PropertyInfo() = GetType(T).GetProperties()
For Each prop As PropertyInfo In properties
If prop.Name = rootPart Then
If nested Then
'This is where my issue is'
Return Convert.ToBoolean(
prop.PropertyType.InvokeMember("IsValidSearchProperty",
BindingFlags.InvokeMethod Or BindingFlags.Public Or BindingFlags.Static Or BindingFlags.FlattenHierarchy,
Nothing, Nothing, New Object() {name.Substring(name.IndexOf(".") + 1)})
)
Else
Return True
End If
End If
Next
Return False
End Function
End Class
这很好用,除非我试图验证在类层次结构中超过 1 层的嵌套属性。例如:
'Pseudocode Hierarchy
BaseEntity(of T)
PersonEntity : Inherits BaseEntity(Of PersonEntity)
Property FirstName as string
PatientEntity : Inherits PersonEntity
Property PatientType as int
VisitEntity : Inherits BaseEntity(Of VisitEntity)
Property Patient as PatientEntity
按 Patient.FirstName 对访问进行排序工作正常,递归地找到该属性,但是当我尝试根据 Patient.PatientType 对访问进行排序时,找不到 PatientType 属性。IsValidSearchProperty 最初是从查找 Patient 属性的 VisitEntity 调用的,它甚至显示为 PatientEntity 类型,但是当此方法使用 InvokeMember 递归调用自身时(这就是我尝试使用属性 Type 调用它的方式) ,在第二次调用中,GetType(T) 是 PersonEntity 类型,它没有 PatientType。关于如何正确解析嵌套调用中的类型的任何建议?
这个方法会被这样调用:
VisitEntity.IsValidSearchProperty("Patient.FirstName")
VisitEntity.IsValidSearchProperty("Patient.PatientType") '* This one doesn't work
PatientEntity.IsValidSearchProperty("PatientType")
PatientEntity.IsValidSearchProperty("FirstName")
更新
以下是关于我如何使用它的更多信息:
Dim sorts() As String = SortExpression.Split(";")
For Each sort As String In sorts
Dim sortParts() As String = sort.Split(" ")
If VisitEntity.IsValidSearchProperty(sortParts(0)) Then
If sortParts(1).ToLower = "true" Then
visits = visits.OrderBy(Of VisitEntity)(sortParts(0).ToString(), SortDirection.Ascending)
Else
visits = visits.OrderBy(Of VisitEntity)(sortParts(0).ToString(), SortDirection.Descending)
End If
Else
_log.WarnFormat("Found invalid sort property {0}", sortParts(0))
End If
Next
SortExpression 类似于“Patient.PatientType True;Patient.FirstName True”