自己写个类型转换类 Converter.cs

在C#中,似乎没有一种方便的类型转换类,使得当转换失败时,默认返回一个预先设定好的值。

如从数据库中读到一个日期字段reader["time"],将它放到一个DateTime类型变量 myTime 中时,就要做一个类型转换。然而,reader["time"]很有可能为空,所以即使你用

myTime = Convert.ToDateTime(reader["time"].ToString()) ;

也不安全,很可能因为reader["time"]为Null或者不是正确的日期格式而导致程序崩溃。

我希望要一种方便的方式,使得当reader["time"]不是正确的日期格式时,就往myTime中填入一个最小的日期值,告诉程序日期无效,并且不会让程序崩溃。于是自己写了个类型转换类Converter.cs,有了它就可以方便地实现上述的要求。

myTime = Converter.ToDateTime(reader["time"].ToString());

或者你希望用日期最大值来代表无效的日期:

myTime = Converter.ToDateTime(reader["time"].ToString(), DateTime.MaxValue);

 

Converter.cs 源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
/// <summary>
/// 类型转换类
/// </summary>
/// <remarks>
/// 作者:涂鸦 admin@myfootprints.cn
/// </remarks>
public class Converter
{
    public Converter()
    {
        //
        // TODO: Add constructor logic here
        //
    }
 
    public static int ToInt(string value, int errorValue)
    {
        int returnValue;
 
        if (!int.TryParse(value, out returnValue))
        {
            returnValue = errorValue;
        }
 
        return returnValue;
    }
 
    public static int ToInt(string value) {
        return ToInt(value, 0);
    }
 
    public static double ToDouble(string value, double errorValue)
    {
        double returnValue;
 
        if (!double.TryParse(value, out returnValue))
        {
            returnValue = errorValue;
        }
 
        return returnValue;
    }
 
    public static double ToDouble(string value)
    {
        return ToDouble(value, 0.0);
    }
 
    public static DateTime ToDateTime(string value, DateTime errorValue)
    {
        DateTime returnValue;
 
        if (!DateTime.TryParse(value, out returnValue))
        {
            returnValue = errorValue;
        }
 
        return returnValue;
    }
 
    public static DateTime ToDateTime(string value)
    {
        return ToDateTime(value, DateTime.MinValue);
    }
 
    public static bool ToBoolean(string value, bool errorValue)
    {
        bool returnValue;
 
        if (!bool.TryParse(value, out returnValue))
        {
            returnValue = errorValue;
        }
 
        return returnValue;
    }
 
    public static bool ToBoolean(string value)
    {
        return ToBoolean(value, false);
    }
}
 
 

Be the first to rate this post

  • Currently .0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Add comment

Loading