Stringbuilder用法


Stringbuilder搜索類是直接用於字符串操作的類,打個比方把
(1)string aa="123456";
(2)aa+="789";


(3)StringBuilder text=new StringBuilder("123456",12);
(4)text.Append("789");
如果你輸出aa,和text 你會發現他們的輸出內容是一樣的。
但是aa的操作過程實際上是:首先在內存中分配一個地址空間,空間大小是6。
然后執行  aa+="789";的操作,該過程是連接字符串,“123456”和“789”並且在內存中重新分配地址。把aa 的內存地址指向 “123456789”的內存地址。

也就是說在內存中實際上是有兩個空間北分配,第一的內存空間,在后來是由C#的垃圾處理機制來自動處理掉,

如果我們用3 4 句的程序來實現這個過程,那么他是沒有再次分配內存空間的,
他就是在text的內存空間里進行了操作。這里要說明下StringBuilder在生命變量的過程中是可以我們自己來分配他的大小的,如果實際的內容超出內存空間,
他會自動翻倍。

通過上面的例子,我們可以知道 StringBuilder的優越性是在:
第一:他不需要每次都去分配內存空間。所以系統就沒有必要去處理垃圾;
第二:當我們需要多次的對一個字符串進行多次操作的時候,他的效率要遠遠  高  與string

Stringbuilder一般用來拼接sql語句

                string txtmonth = Request.Form["jqxMonth"].ToString();
                string txtyear = Request.Form["txtYear"].ToString();
                string txtRegion = Request.Form["jqxRegion"].ToString();
                StringBuilder StrWhere = new StringBuilder();
                StrWhere.Append(" 1 = 1 ");
                if (txtRegion != "")
                {
                    StrWhere.Append(" AND Region='" + txtRegion + "'");
                }
                if (txtyear != "")
                {
                    if (txtmonth != "")
                        StrWhere.Append(" and Year_Month='" + txtyear + "-" + txtmonth + "'");
                    else
                        StrWhere.Append(" and Year_Month like '%" + txtyear + "%'");
                }
                if (txtApplication != "")
                {
                    StrWhere.Append(" and isnull(Region,'')+isnull(Ori_Currency,'')+isnull(Currency1,'')+isnull(Currency2,'')+isnull(Currency3,'')+isnull(Currency4,'')+isnull(Currency5,'')+isnull(convert(nvarchar(10),Year_Month,120),'')+isnull(cast(Fxrate_CNY as varchar),'')+isnull(cast(Fxrate_EUR as varchar),'')+isnull(cast(Fxrate_HKD as varchar),'')+isnull(cast(Fxrate_TWD as varchar),'')+isnull(Status,'') LIKE '%" + txtApplication + "%'");
                }
                StrWhere.Append(" and IsDel=0");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM