7

私は ReSharper を使用しており、そのデフォルトのルールを守ろうとしています。

コードの一部で、文字列の Property を PascalCase に変更する必要があります。

私は多くの方法を試しましたが、すべて大文字の略語を含むものに対して機能する方法を見つけることができません.

元:

MPSUser --> Still MPSUser (should be MpsUser)
ArticleID --> Still Article ID (Should be ArticleId)
closeMethod --> Works and changes to CloseMethod

String を PascalCase に変換できるメソッドの作成を手伝ってくれる人はいますか? ありがとう!

4

2 に答える 2

4

に変換するために私が知っている唯一の組み込みメソッドPascalCaseTextInfo.ToTitleCaseであり、設計上、すべて大文字の単語を処理しません。これを回避するために、すべての単語部分を検出できるカスタム正規表現を作成し、それらを個別にタイトル/パスカル ケースに変換します。

string ToPascalCase(string s)
{
    // Find word parts using the following rules:
    // 1. all lowercase starting at the beginning is a word
    // 2. all caps is a word.
    // 3. first letter caps, followed by all lowercase is a word
    // 4. the entire string must decompose into words according to 1,2,3.
    // Note that 2&3 together ensure MPSUser is parsed as "MPS" + "User".

    var m = Regex.Match(s, "^(?<word>^[a-z]+|[A-Z]+|[A-Z][a-z]+)+$");
    var g = m.Groups["word"];

    // Take each word and convert individually to TitleCase
    // to generate the final output.  Note the use of ToLower
    // before ToTitleCase because all caps is treated as an abbreviation.
    var t = Thread.CurrentThread.CurrentCulture.TextInfo;
    var sb = new StringBuilder();
    foreach (var c in g.Captures.Cast<Capture>())
        sb.Append(t.ToTitleCase(c.Value.ToLower()));
    return sb.ToString();
}

この関数は、一般的なユース ケースを処理する必要があります。

s           | ToPascalCase(s)
MPSUser     | MpsUser
ArticleID   | ArticleId
closeMethod | CloseMethod
于 2014-04-28T16:14:40.537 に答える