在 .Net 中为复数形式附加“s"的巧妙方法(语法糖) [英] Clever way to append 's' for plural form in .Net (syntactic sugar)
问题描述
我希望能够输入以下内容:
I want to be able to type something like:
Console.WriteLine("You have {0:life/lives} left.", player.Lives);
代替
Console.WriteLine("You have {0} {1} left.", player.Lives, player.Lives == 1 ? "life" : "lives");
所以对于 player.Lives == 1
,输出将是:你还剩 1 条生命.
对于 player.Lives != 1
:你还剩 5 条生命.
so that for player.Lives == 1
the output would be: You have 1 life left.
for player.Lives != 1
: You have 5 lives left.
或
Console.WriteLine("{0:day[s]} till doomsday.", tillDoomsdayTimeSpan);
某些系统内置了该功能.我可以在 C# 中接近该符号吗?
Some systems have that built-in. How close can I get to that notation in C#?
是的,我专门寻找语法糖,而不是确定单数/复数形式的方法.
Yes, I am specifically looking for syntactic sugar, and not a method to determine what singular/plural forms are.
推荐答案
您可以创建一个自定义格式化程序:
You can create a custom formatter that does that:
public class PluralFormatProvider : IFormatProvider, ICustomFormatter {
public object GetFormat(Type formatType) {
return this;
}
public string Format(string format, object arg, IFormatProvider formatProvider) {
string[] forms = format.Split(';');
int value = (int)arg;
int form = value == 1 ? 0 : 1;
return value.ToString() + " " + forms[form];
}
}
Console.WriteLine
方法没有采用自定义格式化程序的重载,因此您必须使用 String.Format
:
The Console.WriteLine
method has no overload that takes a custom formatter, so you have to use String.Format
:
Console.WriteLine(String.Format(
new PluralFormatProvider(),
"You have {0:life;lives} left, {1:apple;apples} and {2:eye;eyes}.",
1, 0, 2)
);
输出:
You have 1 life left, 0 apples and 2 eyes.
注意:这是使格式化程序工作的最低要求,因此它不处理任何其他格式或数据类型.理想情况下,它会检测格式和数据类型,如果字符串中有其他格式或数据类型,则将格式传递给默认格式化程序.
Note: This is the bare minimum to make a formatter work, so it doesn't handle any other formats or data types. Ideally it would detect the format and data type, and pass the formatting on to a default formatter if there is some other formatting or data types in the string.
这篇关于在 .Net 中为复数形式附加“s"的巧妙方法(语法糖)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!