How can I check if a character is a valid Key in VB.NET?
I need to check if a character is a valid Key (type) in VB.NET (I n开发者_如何学Goeed to turn "K" into Keys.K, for example). I am currently doing this to convert it:
Keys.Parse(GetType(Keys), key, False)
However, if key is not valid it throws an exception. How can I check if key is a valid character?
Enums do not have a TryParse method, therefore, you could do something like this:
Public Function IsValidKey(ByVal key As String) As Keys
If Not [Enum].IsDefined(GetType(Keys), key) Then
Return Keys.None
End If
Return CType(Keys.Parse(GetType(Keys), key, False), Keys)
End Function
Use it like this:
Dim k As Keys = IsValidKey("K")
If k <> Keys.None Then
' valid key
else
' invalid key
End If
You should use Keys.TryParse (Available in .Net 4.0). It will return true if key is a valid key, false otherwise (Doesn't throw).
精彩评论