1. ホーム
  2. c#

[解決済み] C#では、ToUpper()とToUpperInvariant()の違いは何ですか?

2022-02-11 05:20:59

質問

C#では、以下の違いは何ですか? ToUpper()ToUpperInvariant() ?

結果が異なる可能性がある例を教えてください。

どのように解決するのですか?

ToUpper は現在のカルチャを使用しています。 ToUpperInvariant は不変の文化を使用します。

典型的な例はトルコで、quot;i" の大文字は "I" ではありません。

その違いを示すサンプルコード。

using System;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;

public class Test
{
    [STAThread]
    static void Main()
    {
        string invariant = "iii".ToUpperInvariant();
        CultureInfo turkey = new CultureInfo("tr-TR");
        Thread.CurrentThread.CurrentCulture = turkey;
        string cultured = "iii".ToUpper();

        Font bigFont = new Font("Arial", 40);
        Form f = new Form {
            Controls = {
                new Label { Text = invariant, Location = new Point(20, 20),
                            Font = bigFont, AutoSize = true},
                new Label { Text = cultured, Location = new Point(20, 100),
                            Font = bigFont, AutoSize = true }
            }
        };        
        Application.Run(f);
    }
}

トルコ語については、こちらをご覧ください。 トルコ語テストのブログ記事 .

他にも、省略文字などに関する様々な大文字小文字の問題があると聞いても驚かない。これは私の頭の中にある一例ですが、何年か前にJavaで文字列を大文字にして "MAIL" と比較したときに、この問題に悩まされたからでもあります。トルコではあまりうまくいきませんでしたが...。