Net Core教程

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

本文主要是介绍asp.net代码练习 work083 类型转换优化,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

webform1.aspx

<%@ 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

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,当然也不是设置的越大越好,还有受其他因素限制。

        }


    }
}

这篇关于asp.net代码练习 work083 类型转换优化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!