string.ToLower() and string.ToLowerInvariant()

后端 未结 4 1744
孤独总比滥情好
孤独总比滥情好 2020-11-28 06:22

What\'s the difference and when to use what? What\'s the risk if I always use ToLower() and what\'s the risk if I always use ToLowerInvariant()?

4条回答
  •  独厮守ぢ
    2020-11-28 07:09

    TL;DR:

    When working with "content" (e.g. articles, posts, comments, names, places, etc.) use ToLower(). When working with "literals" (e.g. command line arguments, custom grammars, strings that should be enums, etc.) use ToLowerInvariant().

    Examples:

    =Using ToLowerInvariant incorrectly=

    In Turkish, DIŞ means "outside" and diş means "tooth". The proper lower casing of DIŞ is dış. So, if you use ToLowerInvariant incorrectly you may have typos in Turkey.

    =Using ToLower incorrectly=

    Now pretend you are writing an SQL parser. Somewhere you will have code that looks like:

    if(operator.ToLower() == "like")
    {
      // Handle an SQL LIKE operator
    }
    

    The SQL grammar does not change when you change cultures. A Frenchman does not write SÉLECTIONNEZ x DE books instead of SELECT X FROM books. However, in order for the above code to work, a Turkish person would need to write SELECT x FROM books WHERE Author LİKE '%Adams%' (note the dot above the capital i, almost impossible to see). This would be quite frustrating for your Turkish user.

提交回复
热议问题