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

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

问题描述

早在VB6,我写了一些功能,将让我的代码,而不必关心和0号'字符串空之间的区别,空,等不必编码时没有杀死我的工作效率更添加特殊情况下的代码来处理可能导致一些无关痛痒的错误的数据;万分之九千九百九十九如果事情我使用一个号码是空,那么我真的把它当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.

所以,我需要编写将接受一个字符串,数据库字段,申请表/ querysting场,???,然后尽一切可能做到把它转换成一个双功能,并返回到调用过程。

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.

我还需要为短裤,INT16,INT32,长期这样做,其他的一切我可能关心。

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 回来。通 0L 的Int64 。等等...

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天全站免登陆