﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-becket-文章分类-C#</title><link>http://www.blogjava.net/ebecket/category/40887.html</link><description>一路风景我一路走着,不管多么疲惫,因为一路的风景很美.......
</description><language>zh-cn</language><lastBuildDate>Mon, 23 Nov 2009 02:27:52 GMT</lastBuildDate><pubDate>Mon, 23 Nov 2009 02:27:52 GMT</pubDate><ttl>60</ttl><item><title> Conversion from Enum to String </title><link>http://www.blogjava.net/ebecket/articles/303083.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Fri, 20 Nov 2009 09:53:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/303083.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/303083.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/303083.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/303083.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/303083.html</trackback:ping><description><![CDATA[<p><font face="Verdana, Arial, Helvetica, sans-serif" size="2">I have an enum SortFilter, which looks like following:</font></p>
<font size="2">
<p style="margin: 0in 0in 0pt"><font color="#0000ff" size="2"><font face="Verdana, Arial, Helvetica, sans-serif"><span style="font-size: 10pt; color: blue; font-family: 'Courier New'">public</span><span style="font-size: 10pt; font-family: 'Courier New'"><span style="color: blue">enum</span><font color="#000000"> SortFilter</font></span></font></font></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font color="#0000ff" size="2"><font color="#000000"><font face="Verdana, Arial, Helvetica, sans-serif">{</font></font></font></span></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font color="#0000ff" size="2"><font color="#000000"><font face="Verdana, Arial, Helvetica, sans-serif">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FirstName,</font></font></font></span></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font color="#0000ff" size="2"><font color="#000000"><font face="Verdana, Arial, Helvetica, sans-serif">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; LastName,</font></font></font></span></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font color="#0000ff" size="2"><font color="#000000"><font face="Verdana, Arial, Helvetica, sans-serif">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Age,</font></font></font></span></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font color="#0000ff" size="2"><font color="#000000"><font face="Verdana, Arial, Helvetica, sans-serif">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Experience</font></font></font></span></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font color="#0000ff" size="2"><font face="Verdana, Arial, Helvetica, sans-serif" color="#000000">}</font></font></span></p>
<p><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Now, let's say I want to display the string value of enum in some control. For that, I will have to convert Enum value to string. For example, I want to add all enum string values to a DropDownList. The following code loops through the enumeration and adds string values to it. Here SortByList is&nbsp;DropDownList.</font></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font face="Verdana, Arial, Helvetica, sans-serif">SortByList<span style="color: red">.</span>Items<span style="color: red">.</span>Clear();</font></span></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; color: green; font-family: 'Courier New'"><font face="Verdana, Arial, Helvetica, sans-serif">// Conversion from Enum to String </font></span></p>
<p style="margin: 0in 0in 0pt"><font face="Verdana, Arial, Helvetica, sans-serif"><span style="font-size: 10pt; color: blue; font-family: 'Courier New'">foreach</span><span style="font-size: 10pt; font-family: 'Courier New'"> (<span style="color: blue">string</span> item <span style="color: blue">in</span> Enum<span style="color: red">.</span>GetNames(<span style="color: blue">typeof</span>(ArrayListBinding<span style="color: red">.</span>SortFilter)))</span></font></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font face="Verdana, Arial, Helvetica, sans-serif">{</font></span></p>
<p style="margin: 0in 0in 0pt"><font face="Verdana, Arial, Helvetica, sans-serif"><span style="font-size: 10pt; font-family: 'Courier New'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SortByList<span style="color: red">.</span>Items<span style="color: red">.</span>Add(item);<br />
</span><span style="font-size: 10pt; font-family: 'Courier New'">}&nbsp;&nbsp;&nbsp;&nbsp; </span></font></p>
<p><font face="Verdana, Arial, Helvetica, sans-serif">This code converts an enum to string:</font></p>
<p><font color="#0000ff" size="2"><font face="Verdana, Arial, Helvetica, sans-serif">string</font></font><font face="Verdana, Arial, Helvetica, sans-serif"><font size="2"> name</font><font color="#ff0000" size="2">=</font><font size="2"> Enum</font><font color="#ff0000" size="2">.</font><font size="2">GetName(</font><font color="#0000ff" size="2">typeof</font><font size="2">(ArrayListBinding<span style="color: red">.</span>SortFilter), SortFilter.FirstName</font></font><font size="2"><font face="Verdana, Arial, Helvetica, sans-serif">); </font></font></p>
<p><font face="Verdana, Arial, Helvetica, sans-serif">Now let's say, you have an enum string value say, "FirstName" and now you want to convert it to Enum value. The following code converts from a string to enum value, where Developer.SortingBy is of type&nbsp;SortFilter enumeration: </font></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; color: green; font-family: 'Courier New'"><font face="Verdana, Arial, Helvetica, sans-serif">// Conversion from String to Enum </font></span></p>
<p style="margin: 0in 0in 0pt"><span style="font-size: 10pt; font-family: 'Courier New'"><font face="Verdana, Arial, Helvetica, sans-serif">Developer<span style="color: red">.</span>SortingBy <span style="color: red">=</span> (SortFilter)Enum<span style="color: red">.</span>Parse(<span style="color: blue">typeof</span>(SortFilter), "FirstName");&nbsp;&nbsp; <br />
</font></span></font></p>
<img src ="http://www.blogjava.net/ebecket/aggbug/303083.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-11-20 17:53 <a href="http://www.blogjava.net/ebecket/articles/303083.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>DateTime.Parse 与DateTime.ParseExact</title><link>http://www.blogjava.net/ebecket/articles/303073.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Fri, 20 Nov 2009 09:00:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/303073.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/303073.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/303073.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/303073.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/303073.html</trackback:ping><description><![CDATA[<h2><a title="Permalink" href="http://maxi326.wordpress.com/2008/12/16/c-use-datetimeparseexact-instead-of-datetimeparse/">C# Use DateTime.ParseExact() instead of&nbsp;DateTime.Parse()</a></h2>
<script src="http://s.wordpress.com/wp-content/plugins/adverts/adsense.js?1" type="text/javascript"></script>
<p>I didn&#8217;t notice this until today, the DateTime I retrieve from my database has the format of yyyy/MM/dd hh:mm:ss.fff</p>
<p>and if I use DateTime.Parse(), the .fff value will be lost.</p>
<p>After searching google, I find out that not only DateTime.Parse() has this one problem, it also has problem with culture setting.</p>
<p>So, whenever you what to parse a DateTime, use DateTime.ParseExact().</p>
<p>Here is an useful example :</p>
<pre class="alt"><span class="kwrd">string</span>[] DateTimeList = {
<span class="str">"yyyy/M/d tt hh:mm:ss"</span>,
<span class="str">"yyyy/MM/dd tt hh:mm:ss"</span>,
<span class="str">"yyyy/MM/dd HH:mm:ss"</span>,
<span class="str">"yyyy/M/d HH:mm:ss"</span>,
<span class="str">"yyyy/M/d"</span>,
<span class="str">"yyyy/MM/dd"</span>
};&nbsp;
DateTime dt = DateTime.ParseExact(<span class="str">" 2008/  3/18   PM 02: 50:23  "</span>,
DateTimeList,CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces
);</pre>
<p>Remember, CultureInfo is important to parsing, for example tt in Chinese will be 上午/下午, in en-US will be AM/PM. You can use CultureInfo.CreateSpecificCulture() to create the culture you need.<br />
A small pattern reference</p>
<table>
    <tbody>
        <tr>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>yyyy</td>
            <td>year &#8216;2009&#8242;</td>
        </tr>
        <tr>
            <td>MM</td>
            <td>month &#8216;04&#8242;</td>
        </tr>
        <tr>
            <td>dd</td>
            <td>day &#8216;17&#8242;</td>
        </tr>
        <tr>
            <td>HH</td>
            <td>24 hour &#8216;23&#8242;</td>
        </tr>
        <tr>
            <td>hh</td>
            <td>12 hour &#8216;11&#8242;</td>
        </tr>
        <tr>
            <td>mm</td>
            <td>minutes &#8216;59&#8242;</td>
        </tr>
        <tr>
            <td>ss</td>
            <td>seconds &#8216;30&#8242;</td>
        </tr>
        <tr>
            <td>tt</td>
            <td>AM/PM</td>
        </tr>
        <tr>
            <td>zzz</td>
            <td>GMT</td>
        </tr>
    </tbody>
</table>
<img src ="http://www.blogjava.net/ebecket/aggbug/303073.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-11-20 17:00 <a href="http://www.blogjava.net/ebecket/articles/303073.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>C#代码与javaScript函数的相互调用</title><link>http://www.blogjava.net/ebecket/articles/302230.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Fri, 13 Nov 2009 07:18:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/302230.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/302230.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/302230.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/302230.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/302230.html</trackback:ping><description><![CDATA[<div class="tit">C#代码与javaScript函数的相互调用</div>
<div class="date">2009年09月29日 星期二 1<font style="background-color: #ffff00">4</font>:32</div>
<table style="table-layout: fixed; width: 100%">
    <tbody>
        <tr>
            <td>
            <div class="cnt" id="blog_text">
            <p>出处:http://dotnet.csdn.net/page/c6e71327-58f8-<font style="background-color: #ffff00">4</font>300-a87d-<font style="background-color: #ffff00">4</font>76c6ac80c<font style="background-color: #ffff00">4</font>e</p>
            <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="http://hi.baidu.com/chaobaojun/blog/item/f307146f314d05d380cb4a03.html">http://hi.baidu.com/chaobaojun/blog/item/f3071<font style="background-color: #ffff00">4</font>6f31<font style="background-color: #ffff00">4</font>d05d380cb<font style="background-color: #ffff00">4</font>a03.html</a></p>
            <p>C#代码与javaScript函数的相互调用</p>
            <p>问：<br />
            1.如何在JavaScript访问C#函数?<br />
            2.如何在JavaScript访问C#变量?<br />
            3.如何在C#中访问JavaScript的已有变量?<br />
            <font style="background-color: #ffff00">4</font>.如何在C#中访问JavaScript函数?</p>
            <p>问题1答案如下：<br />
            javaScript函数中执行C#代码中的函数：<br />
            方法一：1、首先建立一个按钮，在后台将调用或处理的内容写入button_click中; <br />
            2、在前台写一个js函数，内容为document.getElementById("btn1").click(); <br />
            3、在前台或后台调用js函数，激发click事件，等于访问后台c#函数；</p>
            <p>方法二：1、函数声明为public <br />
            后台代码(把public改成protected也可以)<br />
            public string ss()<br />
            {<br />
            return("a"); <br />
            }<br />
            2、在html里用＜%=fucntion()%＞可以调用<br />
            前台脚本<br />
            ＜script language=javascript＞<br />
            var a = "＜%=ss()%＞"; <br />
            alert(a); <br />
            ＜/script＞<br />
            方法三：1、＜script language="javascript"＞<br />
            ＜!--<br />
            function __doPostBack(eventTarget, eventArgument)<br />
            {<br />
            var theForm = document.Form1; //指runat=server的form<br />
            theForm.__EVENTTARGET.value = eventTarget; <br />
            theFrom.__EVENTARGUMENT.value = eventArgument; <br />
            theForm.submit(); <br />
            }<br />
            --＞<br />
            ＜/script＞<br />
            ＜input id="Button1" type="button" name="Button1" value="按钮" onclick="javascript:__doPostBack('Button1','')"＞</p>
            <p>方法四：＜script language="javascript"＞<br />
            function SubmitKeyClick()<br />
            {<br />
            if (event.keyCode == 13)<br />
            {<br />
            event.cancelBubble = true; <br />
            event.returnValue = false; <br />
            document.all.FunName.value="你要调用的函数名"；<br />
            document.form[0].submit(); <br />
            }<br />
            }<br />
            ＜/script＞</p>
            <p>＜INPUT onkeypress="SubmitKeyClick()" id="aaa" type="text"＞<br />
            ＜input type="hidden" name="FunName"＞ 〈！--用来存储你要调用的函数 --〉</p>
            <p>在.CS里有：<br />
            public Page_OnLoad()<br />
            {<br />
            if (!Page.IsPost())<br />
            {<br />
            string strFunName=Request.Form["FunName"]!=null?Request.Form["FunName"]:""; <br />
            //根据传回来的值决定调用哪个函数<br />
            switch(strFunName)<br />
            {<br />
            case "enter()":<br />
            enter() ; //调用该函数<br />
            break; <br />
            case "其他":<br />
            //调用其他函数<br />
            break; <br />
            default:<br />
            //调用默认函数<br />
            break; <br />
            }<br />
            }<br />
            }</p>
            <p>public void enter()<br />
            {<br />
            //&#8230;&#8230;比如计算某值<br />
            }</p>
            <p>问题2.如何在JavaScript访问C#变量?<br />
            答案如下：<br />
            方法一：1、通过页面上隐藏域访问＜input id="xx" type="hidden" runat="server"＞<br />
            方法二：1、如后台定义了PUBLIC STRING N; 前台js中引用该变量的格式为'＜%=n%＞'或"+＜%=n%＞+"<br />
            方法三：1、或者你可以在服务器端变量赋值后在页面注册一段脚本<br />
            "＜script language='javascript'＞var temp=" + tmp + "＜/script＞"<br />
            tmp是后台变量，然后js中可以直接访问temp获得值。</p>
            <p><br />
            3.如何在C#中访问JavaScript的已有变量?</p>
            <p>答案如下：</p>
            <p>方法一：1、前台使用静态文本控件隐藏域，将js变量值写入其中；<br />
            2、后台用request["id"]来获取值；举例：把变量给一个隐藏控件 如lable textbox等document.getElementById("textbox的id").value=js变量值 然后后台取 textbox.text<br />
            <br />
            例：加一个textbox&nbsp;&nbsp;&nbsp; id=text1 <br />
            &nbsp;&nbsp; js变量为 var i="测试"；<br />
            js 里document.getElementById("text1").value=i;<br />
            后台取 就用text1.text;</p>
            <p>方法二：可以用cookie或session;<br />
            <font style="background-color: #ffff00">4</font>.如何在C#中访问JavaScript函数?<br />
            答案如下：<br />
            c#代码中执行javaScript函数：<br />
            方法一：1、Page.RegisterStartupScript("ggg","＜script＞SetVisible(1); ＜/script＞"); <br />
            方法二：使用Literal类，然后<br />
            private void Button2_Click(object sender, System.EventArgs e)<br />
            {<br />
            string str; <br />
            str="＜script language='javascript'＞"; <br />
            str+="selectRange()"; <br />
            str+="＜/script＞"; <br />
            //Literal1.Visible=true; <br />
            Literal1.Text=str; <br />
            }</p>
            <p>文章出处：DIY部落(<a href="http://www.diybl.com/course/1_web/%20/jsjs/200798/71020.html">http://www.diybl.com/course/1_web/javascript/jsjs/200798/71020.html</a>)</p>
            <p>今天试着研究了一下服务器控件来控制JS代码（可见不仅仅HTML控件可以调用JS<nobr style="font-size: 14px; color: #6600ff; line-height: 17pt; border-bottom: #6600ff 1px dotted; background-color: transparent; text-decoration: underline">方法</nobr>，服务器控件也可以调用JS方法），</p>
            <p>　　本人觉得有点实用，现分享如下：</p>
            <p>　　前台代码如下：</p>
            <p><code><font face="新宋体">js方法：&lt;script language="javascript"&gt;<br />
            function check()<br />
            {<br />
            　　if(document.all("CheckBox1").checked==true)<br />
            　　{<br />
            　　　 alert("OK");<br />
            　　　//document.getElementById('TextBox1').style.visibility="hidden";<br />
            　　　document.all('TextBox1').style.display="none"; //两种方法均可控制TextBox的显示与隐藏。<br />
            　　}<br />
            　　else<br />
            　　{<br />
            　　 //document.getElementById('TextBox1').style.visibility="visible";<br />
            　　 document.all('TextBox1').style.display="block";　//两种方法均可控制TextBox的显示与隐藏。<br />
            　　}<br />
            }<br />
            &lt;/script&gt;</font></code></p>
            <p><clk style="font-size: 14px; line-height: 17pt"></clk>　　一个TextBox和一个CheckBox。<nobr style="font-size: 14px; color: #6600ff; line-height: 17pt; border-bottom: #6600ff 1px dotted; background-color: transparent; text-decoration: underline">效果</nobr>通过点击CheckBox来控制TextBox的显示与隐藏。</p>
            <p><code><font face="新宋体">&lt;body&gt;<br />
            　　&lt;form id="form1" runat="server"&gt;<br />
            　　&lt;div&gt;<br />
            　　　　&lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt;<br />
            　　　　&lt;asp:CheckBox ID="CheckBox1" runat="server" /&gt;<br />
            　　&lt;/div&gt;<br />
            　　&lt;/form&gt;<br />
            &lt;/body&gt;</font></code></p>
            <p>　　在后台页面来调用JS方法，如下：</p>
            <p><code><font face="新宋体">protected void Page_Load(object sender, EventArgs e)<br />
            　　{<br />
            　　　　CheckBox1.Attributes.Add("onclick","check()");<br />
            　　}</font></code></p>
            <p>　　一般常用的客户端调用的方法如下:</p>
            <p>　　JS方法不变，只是修改控件为HTML控件即可：</p>
            <p><code><font face="新宋体">&lt;body&gt;<br />
            　　&lt;form id="form1" runat="server"&gt;<br />
            　　&lt;div&gt;<br />
            　　　　&amp;nbsp;&lt;input id="TextBox1" type="text" /&gt;<br />
            　　　　&lt;input id="Checkbox1" type="checkbox" onclick="check()" /&gt;<br />
            　　<br />
            　　&lt;/div&gt;<br />
            　　&lt;/form&gt;<br />
            &lt;/body&gt;</font></code></p>
            <p>　　另外还有两种方法，</p>
            <p>　　（1）.直接在服务器控件后面加上onclick事件，后台不写代码。也行，如下：</p>
            <p><code><font face="新宋体">&lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt;<br />
            　　　　&lt;asp:CheckBox ID="CheckBox1" runat="server" onclick="check()" /&gt;</font></code></p>
            <p>　　(2).在工具箱中拖两个HTML控件，然后鼠标右键，选&#8220;作为服务器控件运行&#8221;如下：</p>
            <p><code><font face="新宋体">　　 &lt;input id="TextBox1" type="text" runat="server" /&gt;<br />
            　　&lt;input id="Checkbox1" type="checkbox"　runat="server" /&gt;</font></code></p>
            <p>　　然后再在后台页面来调用JS方法，如下：</p>
            <p><code><font face="新宋体">protected void Page_Load(object sender, EventArgs e)<br />
            　　{<br />
            　　　　CheckBox1.Attributes.Add("onclick","check()");<br />
            　　}</font></code></p>
            </div>
            </td>
        </tr>
    </tbody>
</table>
<img src ="http://www.blogjava.net/ebecket/aggbug/302230.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-11-13 15:18 <a href="http://www.blogjava.net/ebecket/articles/302230.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>去掉末尾的换行符</title><link>http://www.blogjava.net/ebecket/articles/301994.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Wed, 11 Nov 2009 10:19:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/301994.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/301994.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/301994.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/301994.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/301994.html</trackback:ping><description><![CDATA[接下来就是去掉末尾的换行符<br />
　textStr&nbsp;=&nbsp;textStr.TrimEnd((char[])"\n\r".ToCharArray());&nbsp;
<img src ="http://www.blogjava.net/ebecket/aggbug/301994.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-11-11 18:19 <a href="http://www.blogjava.net/ebecket/articles/301994.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Google国际网站遭到域名劫持</title><link>http://www.blogjava.net/ebecket/articles/301927.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Wed, 11 Nov 2009 01:52:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/301927.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/301927.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/301927.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/301927.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/301927.html</trackback:ping><description><![CDATA[今天晚上，包括Google.com在内的绝大多数Google国际网站，例如Google.com、Gmail、Google Reader、Google Docs等，在中国部分省市均出现无法访问的情况。
<p>　　根据我的分析，这次封锁Google的方式并不新鲜，是采用域名劫持（DNS劫持）的方法，通过技术手段，将Google的各类境外域名解析到一个错误的地址，使得Google.com无法访问。前段时间，中央电视台曾经在多个栏目中指责Google，并<a href="http://www.williamlong.info/archives/1835.html" target="_blank">要求</a>其关闭境外网站搜索功能。</p>
<p>　　经过我的测试，使用中国大陆境内的DNS服务器，例如202.96.134.133是无法正确解析出Google的IP地址，而使用境外的OpenDNS进行域名解析，就可以正确解析出Google的IP地址。如下图所示。</p>
<p style="text-align: center"><img alt="Google域名遭到域名劫持" src="http://www.williamlong.info/upload/1841_1.jpg" /></p>
<p>　　解决的方法是使用境外的域名解析服务器（DNS服务器），例如<a href="http://www.williamlong.info/archives/1101.html" target="_blank">OpenDNS</a>的服务，设置方法是，在&#8220;设置&#8221;-&#8220;网络连接&#8221;中找到宽带上网的连接，打开网络连接属性，选择Interner协议（TCP/IP）的属性页里，不要选择自动获取DNS，而要选择&#8220;使用下面的DNS服务器地址&#8221;，首选DNS服务器和备用DNS服务器分别设置为208.67.222.222和208.67.220.220，如下图所示，完成后重新连接上网，就可以摆脱服务商对我们的DNS劫持。</p>
<p align="center"><img alt="网络连接属性" src="http://www.williamlong.info/upload/1101_1.jpg" /></p>
<p align="center"><img alt="网络连接属性" src="http://www.williamlong.info/upload/1101_2.jpg" /></p>
<p>　　对于Google的域名劫持，这已经不是第一次了，<a href="http://www.williamlong.info/archives/377.html" target="_blank">2002年的时候</a>Google的域名就曾经被劫持到百度等网站，<a href="http://www.williamlong.info/archives/542.html" target="_blank">2006年的时候</a>Google.cn被域名劫持到万网的买卖网，这次轮到Google.com了，无论是谁在幕后操纵了这次域名劫持，都会给中国互联网产生极为负面的影响，好在全球13台DNS根服务器全都放在一些法制健全的国家（例如美国、日本），因此这次针对Google的域名劫持对于国外用户没有影响。</p>
<p>　　最后，我强烈谴责这种对于Google网站进行域名劫持的无耻行为。</p>
<p>　　名词解释（来源于维基百科）：</p>
<p>　　DNS是域名系统 (Domain Name Server) 的缩写，该系统用于命名组织到域层次结构中的计算机和网络服务。在Internet上域名与IP地址之间是一对一（或者一对多）的，域名虽然便于人们记忆，但机器之间只能互相认识IP地址，它们之间的转换工作称为域名解析，域名解析需要由专门的域名解析服务器来完成，DNS就是进行域名解析的服务器。</p>
<p>　　域名解析的基本原理是把域名翻译成IP地址，以便计算机能够进一步通信，传递网址和内容等。</p>
<p>　　域名劫持就是在劫持的网络范围内拦截域名解析的请求，分析请求的域名，把审查范围以外的请求放行，否则直接返回假的IP地址或者什么也不做使得请求失去响应，其效果就是对特定的网址不能访问或访问的是假网址。</p>
<img src ="http://www.blogjava.net/ebecket/aggbug/301927.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-11-11 09:52 <a href="http://www.blogjava.net/ebecket/articles/301927.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>基于REST架构的Web Service设计</title><link>http://www.blogjava.net/ebecket/articles/301925.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Wed, 11 Nov 2009 01:48:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/301925.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/301925.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/301925.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/301925.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/301925.html</trackback:ping><description><![CDATA[先前我曾经介绍过利用<a href="http://www.williamlong.info/archives/701.html" target="_blank">Apache Axis</a>实现基于SOAP的Web Service实现技术和相关代码，总的来说，SOAP的Web Service解决方案虽然较为成熟，且安全性较好，但是使用门槛较高，在大并发情况下会有性能问题，在互联网上使用不太普及，因此并不太适合Web 2.0网站服务使用，目前大量的Web 2.0网站使用另外一种解决方案——REST。
<p>　　<strong>REST的架构设计</strong></p>
<p>　　REST（Representational State Transfer）是一种轻量级的Web Service架构风格，其实现和操作明显比SOAP和XML-RPC更为简洁，可以完全通过HTTP协议实现，还可以利用缓存Cache来提高响应速度，性能、效率和易用性上都优于SOAP协议。</p>
<p>　　REST架构遵循了CRUD原则，CRUD原则对于资源只需要四种行为：Create（创建）、Read（读取）、Update（更新）和Delete（删除）就可以完成对其操作和处理。这四个操作是一种原子操作，即一种无法再分的操作，通过它们可以构造复杂的操作过程，正如数学上四则运算是数字的最基本的运算一样。</p>
<p>　　REST架构让人们真正理解我们的网络协议HTTP本来面貌，对资源的操作包括获取、创建、修改和删除资源的操作正好对应HTTP协议提供的GET、POST、PUT和DELETE方法，因此REST把HTTP对一个URL资源的操作限制在GET、POST、PUT和DELETE这四个之内。这种针对网络应用的设计和开发方式，可以降低开发的复杂性，提高系统的可伸缩性。</p>
<p>　　<strong>REST的设计准则</strong></p>
<p>　　REST架构是针对Web应用而设计的，其目的是为了降低开发的复杂性，提高系统的可伸缩性。REST提出了如下设计准则：</p>
<p>　　网络上的所有事物都被抽象为资源（resource）；</p>
<p>　　每个资源对应一个唯一的资源标识符（resource identifier）；</p>
<p>　　通过通用的连接器接口（generic connector interface）对资源进行操作；</p>
<p>　　对资源的各种操作不会改变资源标识符；</p>
<p>　　所有的操作都是无状态的（stateless）。</p>
<p>　　<strong>使用REST架构</strong></p>
<p>　　对于开发人员来说，关心的是如何使用REST架构，这里我们来简单谈谈这个问题。REST不仅仅是一种崭新的架构，它带来的更是一种全新的Web开发过程中的思维方式：通过URL来设计系统结构。REST是一套简单的设计原则、一种架构风格（或模式），不是一种具体的标准或架构。REST有很多成功的使用案例，著名的Delicious和Flickr都提供基于REST风格的API使用，客户端调用也极其方便，下面是我用ASP写的一个很简单的REST举例，从中可以看出REST是多么的简单易用。</p>
<p>　　客户端代码：</p>
<div class="code" lang="asp">
<p>Private Function httpGet(url, method, data)<br />
&nbsp;&nbsp;&nbsp; Dim xmlhttp<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")<br />
&nbsp;&nbsp;&nbsp; xmlhttp.open method, url + "?" + data, False<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Length", Len(data)<br />
&nbsp;&nbsp;&nbsp; xmlhttp.send (Null)<br />
&nbsp;&nbsp;&nbsp; If (xmlhttp.Status = 200) Then httpGet = xmlhttp.responseText<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Nothing<br />
End Function</p>
<p>Private Function httpPost(url, method, data)<br />
&nbsp;&nbsp;&nbsp; Dim xmlhttp<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")<br />
&nbsp;&nbsp;&nbsp; xmlhttp.open method, url, False<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Length", Len(data)<br />
&nbsp;&nbsp;&nbsp; xmlhttp.send (data)<br />
&nbsp;&nbsp;&nbsp; If (xmlhttp.Status = 200) Then httpPost = xmlhttp.responseText<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Nothing<br />
End Function</p>
<p>Private Function httpPut(url, method, data)<br />
&nbsp;&nbsp;&nbsp; Dim xmlhttp<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")<br />
&nbsp;&nbsp;&nbsp; xmlhttp.open method, url, False<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Length", Len(data)<br />
&nbsp;&nbsp;&nbsp; xmlhttp.send (data)<br />
&nbsp;&nbsp;&nbsp; If xmlhttp.Status &gt;= 400 And xmlhttp.Status &lt;= 599 Then<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; response.write " Error Occurred : " &amp; xmlhttp.Status &amp; " - " &amp; xmlhttp.statusText<br />
&nbsp;&nbsp;&nbsp; Else<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; response.write xmlhttp.responseText<br />
&nbsp;&nbsp;&nbsp; End If<br />
&nbsp;&nbsp;&nbsp; If (xmlhttp.Status = 200) Then httpPut = xmlhttp.responseText<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Nothing<br />
End Function</p>
<p>Private Function httpDelete(url, method, data)<br />
&nbsp;&nbsp;&nbsp; Dim xmlhttp<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")<br />
&nbsp;&nbsp;&nbsp; xmlhttp.open method, url + "?" + data, False<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"<br />
&nbsp;&nbsp;&nbsp; xmlhttp.setRequestHeader "Content-Length", Len(data)<br />
&nbsp;&nbsp;&nbsp; xmlhttp.send (Null)<br />
&nbsp;&nbsp;&nbsp; If xmlhttp.Status &gt;= 400 And xmlhttp.Status &lt;= 599 Then<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; response.write " Error Occurred : " &amp; xmlhttp.Status &amp; " - " &amp; xmlhttp.statusText<br />
&nbsp;&nbsp;&nbsp; Else<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; response.write xmlhttp.responseText<br />
&nbsp;&nbsp;&nbsp; End If<br />
&nbsp;&nbsp;&nbsp; If (xmlhttp.Status = 200) Then httpDelete = xmlhttp.responseText<br />
&nbsp;&nbsp;&nbsp; Set xmlhttp = Nothing<br />
End Function</p>
<p>response.write httpPost("http://localhost/rest/service.asp", "POST", "do=POST")<br />
response.write httpGet("http://localhost/rest/service.asp", "GET", "do=GET")<br />
response.write httpPut("http://localhost/rest/service.asp", "PUT", "do=PUT")<br />
response.write httpDelete("http://localhost/rest/service.asp", "DELETE", "do=DELETE")</p>
</div>
<p>　　服务端代码：</p>
<div class="code" lang="asp">Response.Write Request.ServerVariables("REQUEST_METHOD")<br />
If (Request.ServerVariables("REQUEST_METHOD")="GET") Then<br />
&nbsp;Response.Write "DO GET" + Request("do")<br />
ElseIf (Request.ServerVariables("REQUEST_METHOD")="POST") Then<br />
&nbsp;Response.Write "DO POST" + Request("do")<br />
ElseIf (Request.ServerVariables("REQUEST_METHOD")="PUT") Then<br />
&nbsp;Response.Write "DO PUT" + Request("do")<br />
ElseIf (Request.ServerVariables("REQUEST_METHOD")="DELETE") Then<br />
&nbsp;Response.Write "DO DELETE" + Request("do")<br />
End if</div>
<p>　　需要注意的是，IIS服务器默认是不支持ASP文件的PUT和DELETE操作，默认会返回&#8220;403 - Forbidden&#8221;错误，因此需要修改IIS的设置，修改方法是：管理根据－IIS信息服务器－网站－属性－主目录－应用程序配置－配置－映射，选择ASP － 编辑 － 修改为全部动作。</p>
<p>　　关于更多关于REST方面的知识，建议阅读《RESTful Web Services》这本书。</p>
<img src ="http://www.blogjava.net/ebecket/aggbug/301925.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-11-11 09:48 <a href="http://www.blogjava.net/ebecket/articles/301925.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>C# List 用法</title><link>http://www.blogjava.net/ebecket/articles/301842.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Tue, 10 Nov 2009 07:46:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/301842.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/301842.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/301842.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/301842.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/301842.html</trackback:ping><description><![CDATA[<div id="a">
<h1>C# List Examples</h1>
by Sam Allen - Updated September 6, 2009</div>
<div style="margin-right: 300px">
<p><strong>Problem.</strong> You have questions about the List collection in the .NET <font size="+0">F</font>ramework, which is located in the System.Collections.Generic namespace. You want to see examples o<font size="+0">f</font> using List and also explore some o<font size="+0">f</font> the many use<font size="+0">f</font>ul methods it provides, making it an ideal type <font size="+0">f</font>or dynamically adding data. <strong>Solution.</strong> This document has lots o<font size="+0">f</font> tips and resources on the List constructed type, with examples using the C# programming language.
<pre><strong style="background: #66cdaa; color: #fff">--- Key points: ---                                           </strong>
<span style="background: #f8f8ff">    Lists are dynamic arrays in the C# language.              </span>
<span style="background: #f8f8ff">    They can grow as needed when you add elements.            </span>
<span style="background: #f8f8ff">    They are called generic collections and constructed types.</span>
<span style="background: #f8f8ff">    You need to use &lt; and &gt; in the List declaration.          </span></pre>
<h2>1. Adding values</h2>
<p>Here we see how to <strong>declare</strong> a new List o<font size="+0">f</font> int values and add integers to it. This example shows how you can create a new List o<font size="+0">f</font> unspeci<font size="+0">f</font>ied size, and add <font size="+0">f</font>our prime numbers to it. Importantly, the angle brackets are part o<font size="+0">f</font> the declaration type, not conditional operators that mean less or more than. They are treated di<font size="+0">f</font><font size="+0">f</font>erently in the language.
<pre><strong style="background: khaki">~~~ Program that adds elements to List (C#) ~~~</strong>
using System.Collections.Generic;
class Program
{
static void Main()
{
List&lt;int&gt; list = <strong>new List&lt;int&gt;()</strong>;
list.<strong>Add</strong>(2);
list.<strong>Add</strong>(3);
list.<strong>Add</strong>(5);
list.<strong>Add</strong>(7);
}
}</pre>
<p><strong>Adding objects.</strong> The above example shows how you can add a primitive type such as integer to a List collection, but the List collection can receive re<font size="+0">f</font>erence types and object instances. There is more in<font size="+0">f</font>ormation on adding objects with the Add method on this site. [<a href="http://dotnetperls.com/list-add">C# List Add Method</a> - dotnetperls.com]
<h2>2. Loops</h2>
<p>Here we see how you can <strong>loop through</strong> your List with <font size="+0">f</font>or and <font size="+0">f</font>oreach loops. This is a very common operation when using List. The syntax is the same as that <font size="+0">f</font>or an array, except your use Count, not Length <font size="+0">f</font>or the upper bound. You can also loop backwards through your List by reversing the <font size="+0">f</font>or loop iteration variables. Start with list.Count - 1, and proceed decrementing to &gt;= 0.
<pre><strong style="background: #dcdcdc">~~~ Program that loops through List (C#) ~~~</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List&lt;int&gt; list = new List&lt;int&gt;();
list.Add(2);
list.Add(3);
list.Add(7);
<strong><font size="+0">f</font>oreach</strong> (int prime in list) <em>// Loop through List with <font size="+0">f</font>oreach</em>
{
Console.WriteLine(prime);
}
<strong><font size="+0">f</font>or</strong> (int i = 0; i &lt; list.Count; i++) <em>// Loop through List with <font size="+0">f</font>or</em>
{
Console.WriteLine(list[i]);
}
}
}
<strong style="background: #dcdcdc">~~~ Output o<font size="+0">f</font> the program ~~~</strong>
(Repeated twice)
2
3
7</pre>
<h2>3. Counting elements</h2>
<p>To get the number o<font size="+0">f</font> elements in your List, access the <strong>Count</strong> property. This is <font size="+0">f</font>ast to access, i<font size="+0">f</font> you avoid the Count() extension method. Count is equal to Length on arrays. See the section "Clearing List" <font size="+0">f</font>or an example on using the Count property.
<h2>4. Clearing List—setting to null</h2>
<p>Here we see how to use the <strong>Clear</strong> method, along with the Count property, to erase all the elements in your List. Be<font size="+0">f</font>ore Clear is called, this List has 3 elements; a<font size="+0">f</font>ter Clear is called, it has 0 elements. Alternatively, you can assign the List to null instead o<font size="+0">f</font> calling Clear, with similar per<font size="+0">f</font>ormance. However, a<font size="+0">f</font>ter assigning to null, you must call the constructor again.
<pre><strong style="background: beige">=== Program that counts List (C#) ===</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List&lt;bool&gt; list = new List&lt;bool&gt;();
list.Add(true);
list.Add(<font size="+0">f</font>alse);
list.Add(true);
Console.WriteLine(list.Count); <em>// 3</em>
list.<strong>Clear</strong>();
Console.WriteLine(list.Count); <em>// 0</em>
}
}
<strong style="background: beige">=== Output o<font size="+0">f</font> the program ===</strong>
3
0</pre>
<h2>5. Copying array to List</h2>
<p>Here we see an easy way to create a new List with the elements in an <strong>array</strong> that already exists. You can use the List constructor and pass it the array as the parameter. List receives this parameter, and <font size="+0">f</font>ills its values <font size="+0">f</font>rom it.
<pre><strong style="background: #ffe4e1">--- Program that copies array to List (C#) ---</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] arr = new int[3]; <em>// New array with 3 elements</em>
arr[0] = 2;
arr[1] = 3;
arr[2] = 5;
List&lt;int&gt; list = <strong>new List&lt;int&gt;(arr)</strong>; <em>// Copy to List</em>
Console.WriteLine(list.Count);       <em>// 3 elements in List</em>
}
}
<strong style="background: #ffe4e1">--- Output o<font size="+0">f</font> the program ---</strong>
Indicates number o<font size="+0">f</font> elements.
3</pre>
<p><strong>Notes on the example.</strong> It is use<font size="+0">f</font>ul to use the List constructor code here to create a new List <font size="+0">f</font>rom Dictionary keys. This will give you a List o<font size="+0">f</font> the Dictionary keys. The array element type must match the type o<font size="+0">f</font> the List elements, or the compiler will re<font size="+0">f</font>use to compile your code.
<h2>6. <font style="background-color: #ffff00">Find</font>ing elements</h2>
<p>Here we an example o<font size="+0">f</font> how you can <strong>test</strong> each element in your List <font size="+0">f</font>or a certain value. This shows the <font size="+0">f</font>oreach loop, which tests to see i<font size="+0">f</font> 3 is in the List o<font size="+0">f</font> prime numbers. Note that more advanced List methods are available to <font style="background-color: #ffff00">find</font> matches in the List, but they o<font size="+0">f</font>ten aren't any better than this loop. They can sometimes result in shorter code. [<a href="http://dotnetperls.com/list-find-methods">C# List <font style="background-color: #ffff00">Find</font> Methods <font size="+0">f</font>or Searching List</a> - dotnetperls.com]
<pre><strong style="background: #7fffd4">~~~ Program that uses <font size="+0">f</font>oreach on List (C#) ~~~</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
<em>// New list <font size="+0">f</font>or example</em>
List&lt;int&gt; primes = new List&lt;int&gt;(new int[] { 2, 3, 5 });
<em>// See i<font size="+0">f</font> List contains 3</em>
<strong><font size="+0">f</font>oreach</strong> (int number in primes)
{
i<font size="+0">f</font> (number == 3) <em>// Will match once</em>
{
Console.WriteLine("Contains 3");
}
}
}
}
<strong style="background: #7fffd4">~~~ Output o<font size="+0">f</font> the program ~~~</strong>
Contains 3</pre>
<h2>7. Using capacity</h2>
<p>You can use the <strong>Capacity</strong> property on List, or pass an integer into the constructor, to improve allocation per<font size="+0">f</font>ormance when using List. The author's research shows that capacity can improve per<font size="+0">f</font>ormance by nearly 2x <font size="+0">f</font>or adding elements. Note however that this is not usually a per<font size="+0">f</font>ormance bottleneck in programs that access data. [<a href="http://dotnetperls.com/capacity">C# Capacity Property</a> - dotnetperls.com]
<p><strong>TrimExcess method.</strong> There is the TrimExcess method on List as well, but its usage is very limited and I have never needed to use it. It reduces the memory used. Note: "The TrimExcess method does nothing i<font size="+0">f</font> the list is at more than 90 percent o<font size="+0">f</font> capacity". [<a href="http://msdn.microsoft.com/en-us/library/ms132207.aspx">List(T).TrimExcess Method</a> - MSDN]
<h2>8. Using BinarySearch</h2>
<p>You can use the <strong>binary search</strong> algorithm on List with the instance BinarySearch method. Binary search uses guesses to <font style="background-color: #ffff00">find</font> the correct element much <font size="+0">f</font>aster than linear searching. It is o<font size="+0">f</font>ten much slower than Dictionary. [<a href="http://dotnetperls.com/binarysearch-list">C# BinarySearch List</a> - dotnetperls.com]
<h2>9. Using AddRange and InsertRange</h2>
<p>You can use AddRange and InsertRange to add or insert <strong>collections</strong> o<font size="+0">f</font> elements into your existing List. This can make your code simpler. See an example o<font size="+0">f</font> these methods on this site. [<a href="http://dotnetperls.com/list-addrange">C# List AddRange Use</a> - dotnetperls.com]
<h2>10. Using <font size="+0">F</font>orEach <u>method</u></h2>
<p>Sometimes you may not want to write a regular <font size="+0">f</font>oreach loop, which makes <font size="+0">F</font>orEach use<font size="+0">f</font>ul. This accepts an <strong>Action</strong>, which is a void delegate method. Be very cautious when you use Predicates and Actions, because they can decrease the readability o<font size="+0">f</font> your code.
<p><strong>Another use<font size="+0">f</font>ul method.</strong> There is a True<font size="+0">F</font>orAll method that accepts a Predicate. I<font size="+0">f</font> the Predicate returns true <font size="+0">f</font>or each element in your List, the True<font size="+0">F</font>orAll method will return true also. Else, it will return <font size="+0">f</font>alse.
<h2>11. Using Join—string List</h2>
<p>Here we see how you can use string.Join on a List o<font size="+0">f</font> strings. This is use<font size="+0">f</font>ul when you need to turn several strings into one <strong>comma-delimited</strong> string. It requires the ToArray instance method on List. The biggest advantage o<font size="+0">f</font> Join here is that no trailing comma is present on the resulting string, which would be present in a loop where each string is appended.
<pre><strong style="background: #ffa07a">=== Program that joins List (C#) ===</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
<em>// List o<font size="+0">f</font> cities we need to join</em>
List&lt;string&gt; cities = new List&lt;string&gt;();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
<em>// Join strings into one CSV line</em>
string line = string.<strong>Join</strong>(",", cities.<strong>ToArray()</strong>);
Console.WriteLine(line);
}
}
<strong style="background: #ffa07a">=== Output o<font size="+0">f</font> the program ===</strong>
New York,Mumbai,Berlin,Istanbul</pre>
<h2>12. Getting List <font size="+0">f</font>rom Keys in Dictionary</h2>
<p>Here we see how you can use the List constructor to get a List o<font size="+0">f</font> keys in your Dictionary collection. This gives you a simple way to iterate over Dictionary keys, or store them elsewhere. The Keys instance property accessor on Dictionary returns an enumerable collection o<font size="+0">f</font> keys, which can be passed to the List constructor as a parameter.
<pre><strong style="background: #dcdcdc">::: Program that converts Keys (C#) :::</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
<em>// Populate example Dictionary</em>
var dict = new Dictionary&lt;int, bool&gt;();
dict.Add(3, true);
dict.Add(5, <font size="+0">f</font>alse);
<em>// Get a List o<font size="+0">f</font> all the Keys</em>
List&lt;int&gt; keys = new <strong>List&lt;int&gt;(dict.Keys)</strong>;
<font size="+0">f</font>oreach (int key in keys)
{
Console.WriteLine(key);
}
}
}
<strong style="background: #dcdcdc">::: Output o<font size="+0">f</font> the program :::</strong>
3, 5</pre>
<h2>13. Inserting elements</h2>
<p>Here we see how you can <strong>insert</strong> an element into your List at any position. The string "dalmation" is inserted into index 1, which makes it become the second element in the List. Note that i<font size="+0">f</font> you have to Insert elements extensively, you should consider the Queue and LinkedList collections <font size="+0">f</font>or better per<font size="+0">f</font>ormance. Additionally, a Queue may provide clearer usage o<font size="+0">f</font> the collection in your code.
<pre><strong style="background: #fff0f5">~~~ Program that inserts into List (C#) ~~~</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List&lt;string&gt; dogs = new List&lt;string&gt;(); <em>// Example List</em>
dogs.Add("spaniel");         <em>// Contains: spaniel</em>
dogs.Add("beagle");          <em>// Contains: spaniel, beagle</em>
dogs.<strong>Insert</strong>(1, "dalmation"); <em>// Contains: spaniel, dalmation, beagle</em>
<font size="+0">f</font>oreach (string dog in dogs) <em>// Display <font size="+0">f</font>or veri<font size="+0">f</font>ication</em>
{
Console.WriteLine(dog);
}
}
}
<strong style="background: #fff0f5">~~~ Output o<font size="+0">f</font> the program ~~~</strong>
spaniel
dalmation
beagle</pre>
<h2>14. Removing elements</h2>
<p>The removal methods on List are covered in depth in another article on this site. It contains examples <font size="+0">f</font>or Remove, RemoveAt, RemoveAll, and RemoveRange, along with the author's notes. [<a href="http://dotnetperls.com/list-remove">C# List Remove Methods</a> - dotnetperls.com]
<h2>15. Sorting and reversing</h2>
<p>You can use the power<font size="+0">f</font>ul <strong>Sort</strong> and Reverse methods in your List collection. These allow you to order your List in ascending or descending order. Additionally, you can use Reverse even when your List is not presorted. There is more in<font size="+0">f</font>ormation on these topics, as well as sorting your List with LINQ on a property on this site. [<a href="http://dotnetperls.com/sort-list">C# Sort List Method, Sorting and Reversing Lists</a> - dotnetperls.com]
<h2>16. Converting List to array</h2>
<p>You can convert your List to an <strong>array</strong> o<font size="+0">f</font> the same type using the instance method ToArray. There are examples o<font size="+0">f</font> this conversion, and the opposite, on this site. [<a href="http://dotnetperls.com/convert-list-array">C# Convert List to Array</a> - dotnetperls.com]
<h2>17. Getting range o<font size="+0">f</font> elements</h2>
<p>Here we see how you can get a range o<font size="+0">f</font> elements in your List collection using the <strong>GetRange</strong> instance method. This is similar to the Take and Skip methods <font size="+0">f</font>rom LINQ, but has di<font size="+0">f</font><font size="+0">f</font>erent syntax.
<pre><strong style="background: khaki">--- Program that gets ranges <font size="+0">f</font>rom List (C#) ---</strong>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List&lt;string&gt; rivers = new List&lt;string&gt;(new string[]
{
"nile",
"amazon",     <em>// River 2</em>
"yangtze",    <em>// River 3</em>
"mississippi",
"yellow"
});
<em>// Get rivers 2 through 3</em>
List&lt;string&gt; range = rivers.<strong>GetRange</strong>(1, 2);
<font size="+0">f</font>oreach (string river in range)
{
Console.WriteLine(river);
}
}
}
<strong style="background: khaki">--- Output o<font size="+0">f</font> the program ---</strong>
amazon
yangtze</pre>
<h2>18. Testing Lists <font size="+0">f</font>or equality</h2>
<p>Sometimes you may need to test two Lists <font size="+0">f</font>or equality, even when their elements are unordered. You can do this by sorting both o<font size="+0">f</font> them and then comparing, or by using a custom List equality method. This site contains an example o<font size="+0">f</font> a method that tests lists <font size="+0">f</font>or equality in an unordered way. [<a href="http://dotnetperls.com/list-equals">C# List Element Equality</a> - dotnetperls.com]
<h2>19. Using List with structs</h2>
<p>When using List, you can improve per<font size="+0">f</font>ormance and reduce memory usage with <strong>structs</strong> instead o<font size="+0">f</font> classes. A List o<font size="+0">f</font> structs is allocated in contiguous memory, unlike a List o<font size="+0">f</font> classes. This is an advanced optimization. Note that in many cases using structs will actually decrease the per<font size="+0">f</font>ormance when they are used as parameters in methods such as those on the List type.
<h2>20. Using var keyword</h2>
<p>Here we see how you can use List collections with the var keyword. This can greatly <strong>shorten</strong> your lines o<font size="+0">f</font> code, which sometimes improves readability. The var keyword has no e<font size="+0">f</font><font size="+0">f</font>ect on per<font size="+0">f</font>ormance, only readability <font size="+0">f</font>or programmers.
<pre><strong style="background: beige">~~~ Program that uses var with List (C#) ~~~</strong>
using System.Collections.Generic;
class Program
{
static void Main()
{
<strong>var list1</strong> = new List&lt;int&gt;();       <em>// &lt;- var keyword used</em>
List&lt;int&gt; list2 = new List&lt;int&gt;(); <em>// &lt;- Is equivalent to</em>
}
}</pre>
<h2>21. Summary</h2>
<p>Here we saw lots o<font size="+0">f</font> examples with the <strong>List</strong> constructed type. You will <font style="background-color: #ffff00">find</font> that List is power<font size="+0">f</font>ul and per<font size="+0">f</font>orms well. It provides <font size="+0">f</font>lexible allocation and growth, making it much easier to use than arrays. In most programs that do not have memory or per<font size="+0">f</font>ormance constraints and must add elements dynamically, the List constructed type in the C# programming language is ideal.</p>
<br />
<br />
<p>List 类是 <a href="http://www.cftea.com/c/2007/07/WIS4B22S06BLB9CQ.asp" target="_blank">ArrayList</a> 类的泛型等效类，某些情况下，用它比用<a href="http://www.cftea.com/c/2007/07/UNNP5Z3DA9CNPIDB.asp" target="_blank">数组</a>和 ArrayList 都方便。</p>
<p>我们假设有一组数据，其中每一项数据都是一个结构。</p>
<div class="code">public struct Item<br />
{<br />
&nbsp;&nbsp;&nbsp; public int Id;<br />
&nbsp;&nbsp;&nbsp; public string DisplayText;<br />
}</div>
<p>注意结构是不能给实例字段赋值的，即 public int Id = 1 是错误的。</p>
<div class="code">using System.Collections.Generic;<br />
<br />
List&lt;Item&gt; items = new List&lt;Item&gt;();<br />
<br />
//添加<br />
Item item1 = new Item();<br />
item1.Id = 0;<br />
item1.DisplayText = "水星";<br />
items.Add(item1);<br />
<br />
//添加<br />
Item item2 = new Item();<br />
item2.Id = 1;<br />
item2.DisplayText = "地球";<br />
items.Add(item2);<br />
<br />
//修改<br />
<span class="caution">//这里使用的是结构，故不能直接用 items[1].DisplayText = "金星";，如果 Item 是类，则可以直接用。为什么呢？因为结构是按值传递的。</span><br />
Item item = items[1];<br />
item.DisplayText = "金星";<br />
items[1] = item;</div>
<br />
<br />
<br />
<br />
<br />
</div>
<img src ="http://www.blogjava.net/ebecket/aggbug/301842.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-11-10 15:46 <a href="http://www.blogjava.net/ebecket/articles/301842.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>NHibernate学习</title><link>http://www.blogjava.net/ebecket/articles/287093.html</link><dc:creator>becket_zheng</dc:creator><author>becket_zheng</author><pubDate>Fri, 17 Jul 2009 02:16:00 GMT</pubDate><guid>http://www.blogjava.net/ebecket/articles/287093.html</guid><wfw:comment>http://www.blogjava.net/ebecket/comments/287093.html</wfw:comment><comments>http://www.blogjava.net/ebecket/articles/287093.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/ebecket/comments/commentRss/287093.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/ebecket/services/trackbacks/287093.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: NHibernate学习 最近准备学NHibernate,于是网上狂找，看来有不少文章，但仔细看就会明白，搞来搞去，其实就那么几篇大同小异的文章，但还是终于在我们的博客上找到篇好点的，就是下面那篇了，我也不明白是哪为高手写的了，因为转载的太多了，有点糊涂了，也许是张老三的作品吧，但不知道是没有把相关源码共享出来，还是我没有找到，对一个新手来说，就一些文字真的有点困难啊，何况下面的文章可能由...&nbsp;&nbsp;<a href='http://www.blogjava.net/ebecket/articles/287093.html'>阅读全文</a><img src ="http://www.blogjava.net/ebecket/aggbug/287093.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/ebecket/" target="_blank">becket_zheng</a> 2009-07-17 10:16 <a href="http://www.blogjava.net/ebecket/articles/287093.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>