Char.IsSymbol(“*”) is false

前端 未结 3 1790
清酒与你
清酒与你 2020-12-19 02:35

I\'m working on a password validation routine, and am surprised to find that VB does not consider \'*\' to be a symbol per the Char.IsSymbol() check. Here is the output from

相关标签:
3条回答
  • 2020-12-19 03:37

    Maybe you have the compiler option "strict" of, because with

    Char.IsSymbol("*")
    

    I get a compiler error

    BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'.
    

    To define a Character literal in VB.NET, you must add a c to the string, like this:

    Char.IsSymbol("*"c)
    
    0 讨论(0)
  • 2020-12-19 03:38

    Characters that are symbols in this context: UnicodeCategory.MathSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.ModifierSymbol and UnicodeCategory.OtherSymbol from the System.Globalization namespace. These are the Unicode characters designated Sm, Sc, Sk and So, respectively. All other characters return False.

    From the .Net source:

    internal static bool CheckSymbol(UnicodeCategory uc)
    {
        switch (uc)
        {
            case UnicodeCategory.MathSymbol:
            case UnicodeCategory.CurrencySymbol:
            case UnicodeCategory.ModifierSymbol:
            case UnicodeCategory.OtherSymbol:
                return true;
            default:
                return false;
        }
    }
    

    or converted to VB.Net:

    Friend Shared Function CheckSymbol(uc As UnicodeCategory) As Boolean
        Select Case uc
            Case UnicodeCategory.MathSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherSymbol
                Return True
            Case Else
                Return False
        End Select
    End Function
    

    CheckSymbol is called by IsSymbol with the Unicode category of the given char.

    Since the * is in the category OtherPunctuation (you can check this with char.GetUnicodeCategory()), it is not considered a symbol, and the method correctly returns False.

    To answer your question: use char.GetUnicodeCategory() to check which category the character falls in, and decide to include it or not in your own logic.

    0 讨论(0)
  • 2020-12-19 03:38

    If you simply need to know that character is something else than digit or letter, use just

    !char.IsLetterOrDigit(c) 
    

    preferably with

    && !char.IsControl(c)
    
    0 讨论(0)
提交回复
热议问题