在.NET1.1时代,在对数据进行不确定的操作的时候,一般都是采用try-catch-finally这种方法来处理,
在try语句块内,进行我们的数据操作,然后在catch内捕获异常.
但是在2.0里,很多地方我们可以不用 try这种语句块的方式,因为2.0已经新增了一些其它的方法.
比如说我们在进行数据类型转换的时候,
旧的方法
新的方法
还有2.0里新增的Dictionary对象的一个方法TryGetValue
看出来没有?第一个最明显的区别就是代码更加精简啦,其实这倒是其次的.
最主要的,新的方法返回的是一个bool值,而不是抛出异常,我们不用再去进行大量的异常处理.
TryXXX()方法如果返回true的时候,会自动把查找到的值out到之前定义的成员.
在try语句块内,进行我们的数据操作,然后在catch内捕获异常.
但是在2.0里,很多地方我们可以不用 try这种语句块的方式,因为2.0已经新增了一些其它的方法.
比如说我们在进行数据类型转换的时候,
旧的方法
1
int i;
2
try
3
{
4
i = Convert.ToInt32(Request.Params["id"]);
5
}
6
catch (Exception ex)
7
{
8
//Response.Write("出错原因:" + ex.Message;);
9
i = 0; //设置一个默认值
10
}
int i;2
try3
{4
i = Convert.ToInt32(Request.Params["id"]);5
}6
catch (Exception ex)7
{8
//Response.Write("出错原因:" + ex.Message;);9
i = 0; //设置一个默认值10
}新的方法
1
int i;
2
if (!Int32.TryParse(Request.Params["id"],out i))
3
{
4
i = 1;
5
}
int i;2
if (!Int32.TryParse(Request.Params["id"],out i))3
{4
i = 1;5
}还有2.0里新增的Dictionary对象的一个方法TryGetValue
1
string str;
2
Dictionary<int, string> dict = new Dictionary<int, string>();
3
dict.Add(1,"string");
4
if (!dict.TryGetValue(2, out str))
5
{
6
str = "text";
7
}
8
string str;2
Dictionary<int, string> dict = new Dictionary<int, string>();3
dict.Add(1,"string");4
if (!dict.TryGetValue(2, out str))5
{6
str = "text";7
}8

看出来没有?第一个最明显的区别就是代码更加精简啦,其实这倒是其次的.
最主要的,新的方法返回的是一个bool值,而不是抛出异常,我们不用再去进行大量的异常处理.
TryXXX()方法如果返回true的时候,会自动把查找到的值out到之前定义的成员.


浙公网安备 33010602011771号