如何将布尔类型转换为“ON”类型“关闭”使用 String.Format
有没有办法使用字符串格式化程序将布尔类型转换为“ON”/“OFF”,例如:
Dim inpValue as Boolean
Dim outValue = String.Format("0:ON;OFF", inpValue)
' should show OFF as output
无需代码或 IFormatProvider?
Is there are any way to convert Boolean type into "ON"/"OFF" using string formatter, like:
Dim inpValue as Boolean
Dim outValue = String.Format("0:ON;OFF", inpValue)
' should show OFF as output
without code or IFormatProvider?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有什么问题:
What is wrong with:
这是来自另一个问题的疯狂技巧,但它完全不可读。我强烈建议你不要这样做!如果您性格紧张,请立即停止阅读。
这会将
Boolean
转换为-1
或0
,然后使用 自定义数字格式。Here's a crazy trick from another question but it's completely unreadable. I strongly advise you not to do this! If you are of nervous disposition, stop reading now.
This converts the
Boolean
to-1
or0
and then uses a custom numeric format.这应该对您有帮助:
http://www.developmentnow.com/g/ 38_2004_4_0_0_238356/iformatprovider-for-boolean.htm
This should help you:
http://www.developmentnow.com/g/38_2004_4_0_0_238356/iformatprovider-for-boolean.htm
据我所知,没有任何内置支持。但是,根据您拥有的控制权,您可以创建自己的格式提供程序 (IFormatProvider)。以下是对此进行讨论的链接:bool 格式提供程序。
There isn't any built-in support that I am aware of. However, depending on how much control you have, you can create your own format provider (IFormatProvider). Here is a link to a discussion on this: bool format provider.
您无法使用 String.Format 执行此操作(不实现 IFormatProvider 这对于您的目的来说似乎有点过头了),但您可以使用 IIf 在一行中完成此操作:
就我个人而言,我建议使用 If/Else 语句而不是 IIf,因为 IIf 对于某些来自其他语言的程序员来说并不直观。
You can't do this using String.Format (without implementing IFormatProvider which seems like a overkill for your purposes), but you can do it in one line using IIf:
Personally, I recommend using an If/Else statement instead of IIf, as IIf is not intuitive for some programmers coming from other languages.
c# - 不是最优雅但最有效:
string outValue = inpValue.ToString().Replace("False", "OFF").Replace("True", "ON");
c# - not the most elegant but effective:
string outValue = inpValue.ToString().Replace("False", "OFF").Replace("True", "ON");