Helper class to achieve common task

前端 未结 2 747
执笔经年
执笔经年 2020-12-22 06:43

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

For example, I am retrieving some results from Database and then assigning the values to variables. Bu

相关标签:
2条回答
  • 2020-12-22 06:44

    A more radical approach (which would remove the issue) would be to eradicate NULLs from your values altogether.

    The simplest way would be through ISNULL() when you query your database:

    Where now you do

    SELECT MyColumn FROM MyTable
    

    You instead go

    SELECT ISNULL(MyColumn, '') AS MyColumn FROM MyTable
    

    Then you can assume no NULLs will get through to your code.

    0 讨论(0)
  • 2020-12-22 07:09

    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());
    

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

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

    However i would'nt recommend using this.

    0 讨论(0)
提交回复
热议问题