微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net代码练习 work083 类型转换优化

webform1.aspx

@H_502_2@<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="work083.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <Meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>类型转换优化</title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>

webform1.aspx.cs

@H_502_2@using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace work083 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write("字符串类型转换<br>"); Response.Write("1.在NET Framework2.0之前,将字符串转换为数值型常使用Pares()方法<br>"); int.Parse("123"); char.Parse("a"); bool.Parse("True"); Response.Write("如果类型不一致就会抛出异常,会对性能造成影响<br>"); Response.Write("2.在NET Framework2.0之后,可以使用TryPares()替代,减小性能问题。<br>"); string str1 = "123"; string str2 = "ed1"; //out参数,表示可以返回值,b1为true,num1为123 int num1; bool b1 = int.TryParse(str1,out num1); //b2 = false, num2 无值 int num2; bool b2 = int.TryParse(str2, out num2); Response.Write("3.引用类型的转换<br>"); object d1 = "asd"; //强制转换,类型不一致时会抛出异常 string a1 = (string)d1; object d2 = "123"; //System.Text.StringBuilder e1 = (System.Text.StringBuilder)d2; //无法将类型为“System.String”的对象强制转换为类型“System.Text.StringBuilder”。 System.Text.StringBuilder e2 = d2 as System.Text.StringBuilder; Response.Write("4.使用is关键字检查对象的是否兼容<br>"); string p1 = "abcd"; //f1 = true,因为string类使用了接口 bool f1 = p1 is ICloneable; //f2 = true,因为string类是继承于object bool f2 = p1 is object; //f3 = false,因为string类与stringbuilder类之间不存在关系 bool f3 = p1 is System.Text.StringBuilder; //编码过程中应注意尽量减少装箱和拆箱操作。 //装箱操作是指将值类型转换成引用类型。 //拆箱操作是指将引用类型转换成值类型。 Response.Write("5.使用Server.Transfer()方法<br>"); //使用Server.Transfer方法进行重定向,比使用Response.Redirect()方法性能要高。 Response.Write("6.数据库连接对象的优化<br>"); //使用数据库连接时,始终遵循一条原则,尽可能晚打开数据库连接,尽可能早关闭数据库连接。 //优化方法是可以使用连接池,在webconfig中配置连接池 //Data Source = (local);Initial Catalog = test;User ID = sa;Password = 123456; Pooling = true; Min Pool Size=0; Max Pool Size = 200; //连接池认是100,我们可以将最大连接数设置为200,当然也不是设置的越大越好,还有受其他因素限制。 } } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐