2017-07-01 83 views
-1

我正要寫一個方法,它必須決定在比較兩個字符串時是否忽略大小寫。組合StringComparison枚舉

public bool IsCaseSensitiveUsing(StringComparison comparer) 
{ 
    if (comparer == StringComparison.CurrentCulture | 
     comparer == StringComparison.InvariantCulture | 
     comparer == StringComparison.Ordinal)) 
      return true; 

    return false; 

} 

有沒有更好的方法來做到這一點?

+0

怎麼樣只是'StringComparison .OrdinalIgnoreCase'? – Rahul

+0

該方法不會反映真實參數。 'OrdinalIgnoreCase'和'CurrentCultureIgnoreCase'和'InvariantCulture.IgnoreCase'是一樣的嗎? – Mhd

+1

定義「更好」?你可以做'return(int)comparer%2!= 0'或'return!comparer.ToString()。EndsWith(「IgnoreCase」)',它更短,但我不會說更好 –

回答

0

我建議implementng 擴展方法

public static class StringComparisonExtensions { 
    public static bool IsCaseSensitiveUsing(this StringComparison value) { 
     return (value == StringComparison.CurrentCulture || 
       value == StringComparison.InvariantCulture || 
       value == StringComparison.Ordinal); 
    } 
    } 

    .... 

    StringComparison myComparison = ... 

    // Check as if StringComparison has IsCaseSensitiveUsing method: 
    if (myComparison.IsCaseSensitiveUsing()) { 
    ... 
    } 
0

你可以讓一組需要區分大小寫StringComparison值,並在你的方法使用它:

private static readonly ISet<StringComparison> caseSensitive = new HashSet<StringComparison> { 
    StringComparison.CurrentCulture 
, StringComparison.InvariantCulture 
, StringComparison.Ordinal 
}; 
public static bool IsCaseSensitiveUsing(StringComparison comparer) { 
    return caseSensitive.Contains(comparer); 
}