用于从字符串安全转换的辅助函数 [英] Helper functions for safe conversion from strings

查看:43
本文介绍了用于从字符串安全转换的辅助函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

回到 VB6 中,我编写了一些函数,这些函数可以让我编写代码,而不必关心字符串的 null 和 ''、数字的 null 和 0 之间的区别等.在编写代码时,没有什么比必须编写代码更能降低我的工作效率了添加特殊情况代码来处理可能导致一些不相关错误的数据;9999/10000 如果我用作数字的东西是空的,那么我真的把它当作 0.

Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/10000 if something I'm using as a number is null, then really I treat it as 0.

我现在在 C# 中,VB6 和 C# 2005 之间的区别非常广泛......所以我真的不知道从哪里开始编写我的新帮助函数集,或者我什至需要做完全没有.

I'm now in C#, and the difference between VB6 and C# 2005 is quite extensive...so I don't really know where to start to write my new set of helper functions, or if I even need to do them at all.

所以,我需要编写一个函数来接受字符串、数据库字段、请求表单/查询字段、???,然后尽其所能将其转换为 Double,并将其返回给调用过程.

So, I need to write a function that would accept a string, a database field, a request form/querysting field, ???, and then do whatever it could do to turn that into a Double, and return that to the calling procedure.

我还需要为 short、int16、int32、long 以及我可能关心的所有其他东西执行此操作.

I'd also need to do this for shorts, int16, int32, long, everything else I could possibly care about.

然后我会为字符串执行此操作.和日期.

Then I'd do this for strings. And Dates.

这是值得追求的吗?我可以使用框架或 C# 中的某些内容吗?我真的很想要一些东西,可以让我在调用其他函数时使用内联数据,而不必创建临时变量等.

Is this a worthwhile pursuit? Is there something in the framework or C# that I can use instead? I really desire something that would allow me to use data inline in calling other functions, and not having to create temporary variables, etc.

推荐答案

内置了很多转换函数.但是...我不确定他们中的任何一个都完全按照您的意愿行事.通常,.NET 方法在传递无效输入时会谨慎行事,并引发异常.

There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception.

幸运的是,您可以轻松编写实用程序方法来将数字值的字符串表示形式、空字符串、空字符串或空字符串转换为任何输出类型:

Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an empty string empty, or null string to any output type:

public static T SafeConvert<T>(string s, T defaultValue)
{
    if ( string.IsNullOrEmpty(s) )
        return defaultValue;
    return (T)Convert.ChangeType(s, typeof(T));
}

用途:

SafeConvert(null, 0.0) == 0.0;
SafeConvert("", 0.0) == 0.0;
SafeConvert("0", 0.0) == 0.0;

此泛型方法从第二个参数的类型中获取其返回类型,当传递的字符串为 null 或空时,将其用作默认值.传递 0 你会得到一个 In32 回来.通过 0LInt64.等等……

This generic method takes its return type from the type of the second argument, which is used as the default value when the passed string is null or empty. Pass 0 and you'd get an In32 back. Pass 0L, Int64. And so on...

这篇关于用于从字符串安全转换的辅助函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆