Неопределенность со StringComparison
Есть задача написать метод, который проверяет есть ли символ в строке, но с усложнением и прогнать тесты
/// <summary>
/// Returns a value indicating whether a specified string occurs within this string, using the specified comparison rules.
/// </summary>
/// <returns>true if the <paramref name="value"/> parameter occurs within this string, or if <paramref name="value"/> is the <see cref="string.Empty"/>; otherwise, false.</returns>
public static bool IsContainsStringWithStringComparison(string str, string value)
{
return str.Contains(value, StringComparison.CurrentCulture);
}
По тестам есть следующее
[TestCase("encyclopaedia", "enc", "en-US", ExpectedResult = true)]
[TestCase("encyclopaedia", "dia", "en-US", ExpectedResult = true)]
[TestCase("encyclopaedia", "fen", "en-US", ExpectedResult = false)]
[TestCase("encyclopaedia", "ENC", "en-US", ExpectedResult = false)]
[TestCase("ENCYCLOPAEDIA", "enc", "en-US", ExpectedResult = false)]
[TestCase("encyclopaedia", "pæd", "en-US", ExpectedResult = true)]
[TestCase("ENCYCLOPAEDIA", "PÆD", "en-US", ExpectedResult = true)]
[TestCase("encyclopaedia", "PÆD", "en-US", ExpectedResult = false)]
[TestCase("ENCYCLOPAEDIA", "pæd", "en-US", ExpectedResult = false)]
[TestCase("encyclopaedia", "pæd", "se-SE", ExpectedResult = true)]
[TestCase("ENCYCLOPAEDIA", "PÆD", "se-SE", ExpectedResult = true)]
[TestCase("encyclopaedia", "PÆD", "se-SE", ExpectedResult = false)]
[TestCase("ENCYCLOPAEDIA", "pæd", "se-SE", ExpectedResult = false)]
public bool IsContainsStringWithStringComparison(string str, string value, string culture)
{
// Arrange
CultureInfo currentCulture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo(culture);
try
{
// Act
return Contains.IsContainsStringWithStringComparison(str, value);
}
finally
{
// Tear down
CultureInfo.CurrentCulture = currentCulture;
}
}
Так вот, тесты с особыми символами (æ, Æ) не работают как надо и выдают false, хотя как я понял StringComparison.CurrentCulture должен решать проблему.
Ответы (1 шт):
Автор решения: Alexander Petrov
→ Ссылка
Они всё сломали!
Ваш код прекрасно будет работать в .NET Framework и первых версиях .NET Core.
Однако, в .NET 5 перешли на ICU по умолчанию.
Behavior changes when comparing strings on .NET 5+.
Вероятно, самым простым способом будет использовать National Language Support.
Use NLS instead of ICU.
Добавляем в файл проекта:
<ItemGroup>
<RuntimeHostConfigurationOption Include="System.Globalization.UseNls" Value="true" />
</ItemGroup>
Или в файл runtimeconfig.json:
{
"runtimeOptions": {
"configProperties": {
"System.Globalization.UseNls": true
}
}
}