读取动态选择的值 属性,例如(ListItem.Value/.文字)
Read value of dynamically-selected property, e.g. (ListItem.Value/.Text)
我已经看到很多关于 SO 的看似 相关的问题,但我对反射的理解不足以将它们应用到我的案例中。
我有一种方法可以按文本或值对 ListControl.ListItems 进行排序。而不是按字母数字排序,对象必须转换为双精度,然后排序,例如
<asp:ListItem Value="1.1" Text="1.1" />
<asp:ListItem Value="3.4" Text="3.4" />
<asp:ListItem Value="10.587" Text="10.587" />
我的整个方法可能是错误的,但我的方法首先检查是否有任何对象不是数字。如果发现潜在错误(不可解析的值),则该方法回退到字母数字排序:
Public Enum SortBy
Value
Text
End Enum
Public Shared Sub SortListItemsNumerically(lc As ListControl, sortby As SortBy)
Dim parseFail As Boolean = False
Select Case sortby
Case SortBy.Value
If (From li As ListItem In lc.Items
Where Not IsNumeric(li.Value)
Select li).ToArray().Count > 0 Then
parseFail = True
End If
Case SortBy.Text
If (From li As ListItem In lc.Items
Where Not IsNumeric(li.Text)
Select li).ToArray().Count > 0 Then
parseFail = True
End If
End Select
If parseFail Then
' ... fall back
End If
' ... do sort
End Sub
我的问题是 Case
块中有重复代码。是否可以 dynamically/smartly 检查不可解析的值,以避免代码重复?例如:
Dim SomeMagicHere = li.Value/Text
If (From li As ListItem In lc.Items
Where Not IsNumeric(SomeMagicHere)
Select li).ToArray().Count > 0 Then
parseFail = True
End If
在这里做的很快。 GetProperty
和GetValue
是反射方式:
If (From li As ListItem In lc.Items
Where Not IsNumeric(li.GetType().GetProperty(sortby.ToString()).GetValue(li))
Select li).ToArray().Count > 0 Then
parseFail = True
End If
我已经看到很多关于 SO 的看似 相关的问题,但我对反射的理解不足以将它们应用到我的案例中。
我有一种方法可以按文本或值对 ListControl.ListItems 进行排序。而不是按字母数字排序,对象必须转换为双精度,然后排序,例如
<asp:ListItem Value="1.1" Text="1.1" />
<asp:ListItem Value="3.4" Text="3.4" />
<asp:ListItem Value="10.587" Text="10.587" />
我的整个方法可能是错误的,但我的方法首先检查是否有任何对象不是数字。如果发现潜在错误(不可解析的值),则该方法回退到字母数字排序:
Public Enum SortBy
Value
Text
End Enum
Public Shared Sub SortListItemsNumerically(lc As ListControl, sortby As SortBy)
Dim parseFail As Boolean = False
Select Case sortby
Case SortBy.Value
If (From li As ListItem In lc.Items
Where Not IsNumeric(li.Value)
Select li).ToArray().Count > 0 Then
parseFail = True
End If
Case SortBy.Text
If (From li As ListItem In lc.Items
Where Not IsNumeric(li.Text)
Select li).ToArray().Count > 0 Then
parseFail = True
End If
End Select
If parseFail Then
' ... fall back
End If
' ... do sort
End Sub
我的问题是 Case
块中有重复代码。是否可以 dynamically/smartly 检查不可解析的值,以避免代码重复?例如:
Dim SomeMagicHere = li.Value/Text
If (From li As ListItem In lc.Items
Where Not IsNumeric(SomeMagicHere)
Select li).ToArray().Count > 0 Then
parseFail = True
End If
在这里做的很快。 GetProperty
和GetValue
是反射方式:
If (From li As ListItem In lc.Items
Where Not IsNumeric(li.GetType().GetProperty(sortby.ToString()).GetValue(li))
Select li).ToArray().Count > 0 Then
parseFail = True
End If