这个扩展方法是否强制将字符串转换为整数或默认为 0 多余?
我需要一个单行代码将字符串转换为整数,如果字符串无效,则只需将其设置为零。所以我做了以下扩展方法,但我可以想象有一个系统方法可以在一行中完成此操作。
是否有另一种方法可以在一行中完成此操作而无需创建扩展方法?
using System;
namespace TestForceInteger
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("testing".ForceInteger() + 1);
Console.WriteLine("199".ForceInteger() + 1);
int test = StringHelpers.ForceInteger(null);
Console.WriteLine(test + 1);
Console.ReadLine();
//output:
//1
//200
//1
}
}
public static class StringHelpers
{
public static int ForceInteger(this string potentialInteger)
{
int result;
if (int.TryParse(potentialInteger, out result))
return result;
else
return 0;
}
}
}
I needed a one-liner to convert a string to an integer, and if the string is anything invalid, then just set it to zero. So I made the following extension method, but I can imagine there is a system method to do this in one line.
Is there another way to do this in one line without creating an extension method?
using System;
namespace TestForceInteger
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("testing".ForceInteger() + 1);
Console.WriteLine("199".ForceInteger() + 1);
int test = StringHelpers.ForceInteger(null);
Console.WriteLine(test + 1);
Console.ReadLine();
//output:
//1
//200
//1
}
}
public static class StringHelpers
{
public static int ForceInteger(this string potentialInteger)
{
int result;
if (int.TryParse(potentialInteger, out result))
return result;
else
return 0;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不是单行,据我所知,但如果您想避免扩展方法,您可以将结果初始化为 0 并忽略
TryParse
的结果:Not as a one-liner, afaik, but if you want to avoid the extension method you can initialize the result to 0 and ignore the outcome of
TryParse
:这不是框架库的传统方式,不是。
如果您的扩展方法返回一个可以为 null 的 int,那么您的扩展方法会更好,这样您就可以区分“无效”和 0。
Not a conventional way with the framework libraries, no.
Your extension method would be better if it returned a nullable int, so that you could distinguish between "invalid" and 0.
不要为了编写代码的简单性而编写代码,而是按照规范编写代码。创建一个能够真正正确完成工作并注意到无效转换和幻数之间的区别的方法更有意义。当你做这个方法的时候,你只需要做一次,所以要正确地做。然后,在其上方的层中,您可以根据需要将其转换为您正在使用的任何系统。
IE:
Don't code for simplicity of writing your code, code to the specification. It makes far more sense to create a method that actually does the job properly and notes the difference between an invalid conversion and a magic number. When you make this method, you need only make it once, so do it properly. In the layer above it you can then do the conversion you require to whatever system you are using.
I.e.:
用于
确保设置为0。但这绝对是不必要的(请参阅@Anthony对@Paolo答案的评论)
Use
to ensure setting to 0. But this is absolutely unnecessary (see @Anthony's comment to @Paolo's answer)