rhu*_*hes 6 c# asp.net-mvc boolean tostring
我正在将a的值输出boolean到我的MVC视图中,并希望有一个小写true或者false,而不是默认值True或False.
我很感激我可以这样做:
@this.Model.MyBool.ToString().ToLower()
Run Code Online (Sandbox Code Playgroud)
或使用某种扩展方法等...
但它有点挫败了以下目的:
@this.Model.MyBool
Run Code Online (Sandbox Code Playgroud)
我在这里读过这篇文章:为什么Boolean.ToString输出"True"而不是"true"但是大多数答案看起来都很旧.
有没有更现代的方法来做到这一点?
你为什么不试试以下
public string MyStringBool
{
get { return MyBool ? "true" : "false" ; }
}
Run Code Online (Sandbox Code Playgroud)
如果你只想要一个bool变量,你应该使用@Mohamed的方法.否则你可以创建一个扩展方法(正如你自己已经说过的那样):
public static class Extensions
{
public static string ToLowerString(this bool _bool)
{
return _bool.ToString().ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用它:
public static void Main()
{
bool testBoolean = true;
Console.WriteLine(testBoolean.ToLowerString());
}
Run Code Online (Sandbox Code Playgroud)
你也可以这样做,这在语法上感觉比true.ToString().ToLower()(在我看来)更干净:
Json.Encode(true);
Run Code Online (Sandbox Code Playgroud)
然而,在幕后,这比使用.ToString.ToLower()实现的开销要大得多。
Json.Encode(object value)有更多的错误处理,因为它需要考虑更复杂的对象作为参数传递的可能性。
我对此做了一些基准测试,看看实际的差异是什么,并在我的开发盒烤面包机上进行了测试:
var sw0 = Stopwatch.StartNew();
sw0.Stop();
var sw1 = Stopwatch.StartNew();
var t1 = System.Web.Helpers.Json.Encode(true);
var e1 = sw1.ElapsedMilliseconds; // returns 6-9
var sw2 = Stopwatch.StartNew();
var t2 = true.ToString().ToLower();
var e2 = sw2.ElapsedMilliseconds; // returns 0
Run Code Online (Sandbox Code Playgroud)
所以实际上,一次性的影响并不大。
| 归档时间: |
|
| 查看次数: |
9179 次 |
| 最近记录: |