如何将布尔值一般格式化为是/否字符串?

How to generically format a boolean to a Yes/No string?(如何将布尔值一般格式化为是/否字符串?)
本文介绍了如何将布尔值一般格式化为是/否字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据一些布尔变量以不同的语言显示是/否.
是否有根据传递给它的语言环境对其进行格式化的通用方法?
如果没有,除了 boolVar 之外,格式化布尔值的标准方法是什么?Resources.Yes : Resources.No.
我猜这涉及到 boolVar.ToString(IFormatProvider).
我的假设正确吗?

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?
If there isn't, what is the standard way to format a boolean besides boolVar ? Resources.Yes : Resources.No.
I'm guessing that boolVar.ToString(IFormatProvider) is involved.
Is my assumption correct?

推荐答案

框架本身并没有为你提供这个(据我所知).将 true/false 翻译成 yes/no 并没有让我觉得比其他潜在翻译更常见(例如 on/off已选中/未选中只读/读写或其他).

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;
    }
}

用法:

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

这篇关于如何将布尔值一般格式化为是/否字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)