Helper类来实现共同的任务 [英] Helper class to achieve common task

查看:124
本文介绍了Helper类来实现共同的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个辅助类做一些共同的任务。

I would like to create a helper class to do some common task.

例如,我从检索数据库中的一些结果,然后分配给变量。但是,一些在我的记录中的字段可能包含空为好。我想分配的值不包含任何null前检查。

For example, I am retrieving some results from Database and then assigning the values to variables. But some of the fields in my records might contain null as well. I would like to check before assigning that the value does not contain any null.

另外还有一些变量这些都是int类型,所以想解析的具体类型前检查。

Also there are some variable those are type int, so like to check before parsing to the specific type.

int iValue=int.parse(Helpers.IsNull(dr[colName].toString()));
string strValue=Helpers.IsNull(dr[colName].toString());

我应该如何创建一个辅助类,我应该用isNull方法返回什么价值?

How should I create a helper class and what value should I return with IsNull method?

小混淆..

感谢

推荐答案

那么你正在试图acchieve是要避免的NullReferenceException我猜。

Well what you are trying to acchieve is to avoid the NullReferenceException i guess.

您可以通过编写这样一个通用的方法实现这一目标。

You could achieve this by writing a generic method like this

public static TValue GetValueSafe<TValue,TObject>(TObject obj, Func<TObject,TValue> accessor)
{
    if(obj== null)
        return default(TValue);

    return accessor(obj);
}

然后使用它是这样的:

Then use it like this:

string strValue = Helpers.GetValueSafe(dr[colName], o => o.toString());

这要么返回的toString的价值,或者博士[COLNAME] == null返回默认值(串),这是空。

This would either return the value of toString, or if dr[colName] == null returns default(string) which is null.

您可以通过添加一个defaultParameter定义的失败的值exand这一点。

You could exand this by adding a defaultParameter to define a value on "failure".

不过我would'nt建议使用此。

However i would'nt recommend using this.

这篇关于Helper类来实现共同的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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