How to generically format a boolean to a Yes/No string?

前端 未结 4 1345
萌比男神i
萌比男神i 2020-11-30 09:53

I would like to display Yes/No in different languages according to some boolean variable.
Is there a generic way to format it according to the locale passed to it?
I

4条回答
  •  孤城傲影
    2020-11-30 09:59

    The framework itself does not provide this for you (as far as I know). Translating true/false into yes/no does not strike me as more common than other potential translations (such as on/off, checked/unchecked, read-only/read-write or whatever).

    I imagine that the easiest way to encapsulate the behavior is to make an extension method that wraps the construct that you suggest yourself in your question:

    public static class BooleanExtensions
    {
        public static string ToYesNoString(this bool value)
        {
            return value ? Resources.Yes : Resources.No;
        }
    }
    

    Usage:

    bool someValue = GetSomeValue();
    Console.WriteLine(someValue.ToYesNoString());
    

提交回复
热议问题