C# 核心編程結構Ⅰ 筆記

來源:互聯網
上載者:User

On the Windows operating system, an application’s return value is stored within a system environment variable named %ERRORLEVEL%. If you were to create an application that programmatically launches another executable, you can obtain the value of %ERRORLEVEL% using the static System.Diagnostics.Process.ExitCode property.

在Windows作業系統中,應用程式的傳回值(Main()的傳回值)是儲存在一個叫做%ERRORLEVEL%的系統內容變數中.如果我們要建立一個以程式方式啟動另外一個可執行程式,你可以使用靜態System.Diagnostics.Process.ExitCode屬性來擷取%ERRORLEVEL%的值.

 

Using verbatim strings, you can also directly insert a double quote into a literal string by doubling the " token, for example:

Console.WriteLine(@"Cerebus said ""Darrr! Pret-ty sun-sets""");

逐字字串(@開頭的字串)還可以通過重複”標記向一個字面量字串插入一個雙引號.例如:

Console.WriteLine(@"Cerebus said ""Darrr! Pret-ty sun-sets""");

 

a reference type is an object allocated on the garbage-collected man-aged heap. By default, when you perform a test for equality on reference types (via the C# == and != operators), you will be returned true if the references are pointing to the same object in memory. However, even though the string data type is indeed a reference type, the equality operators have been redefined to compare the values of string objects, not the object in memory to which they refer:

參考型別是在記憶體回收託管堆上分配的對象.預設情況下,當我們對參考型別進行相等性測試(通過 == 和 != 運算子)時,如果參考型別指向記憶體中的相同對象,則返回true.然而,儘管字串資料型別確實是參考型別,但是相等性運算子已經被重定義為比較字串對象的值,而不是記憶體中它們引用的對象.

 

Strings Are Immutable

One of the interesting aspects of System.String is that once you assign a string object with its initial value, the character data cannot be changed. At first glance, this might seem like a flat-out lie, given that we are always reassigning strings to new values and due to the fact that the System. String type defines a number of methods that appear to modify the character data in one way or another (uppercasing, lowercasing, etc.). However, if you look more closely at what is happening behind the scenes, you will notice the methods of the string type are in fact returning you a brand-new string object in a modified format:

字串是不可變的

System.Sting一個有趣的方面是,一旦將初始值賦給字串對象,字元資料就不能改變了.咋一看,這可能像一個明顯的謊言.因為我們總是給字串賦新值,而且System.String類型也定義了許多用於以各種方式(大寫,小寫等)修改字元資料的方法.然而,如果細究背後發生的事情,就會注意到字串類型的方法其實返回了一個按修改格式的新字串對象.

 

Given that the string type can be inefficient when used with reckless abandon, the .NET base class libraries provide the System.Text namespace. Within this (relatively small) namespace lives a class named StringBuilder. Like the System.String class, StringBuilder defines methods that allow you to replace or format segments and so forth. When you wish to use this type in your C# code files, your first step is to import the correct namespace:

// StringBuilder lives here!using System.Text;

What is unique about the StringBuilder is that when you call members of this type, you are directly modifying the object’s internal character data (and is thus more efficient), not obtaining a copy of the data in a modified format. When you create an instance of the StringBuilder, you can supply the object’s initial startup values via one of many constructors.

如果隨便棄用的話,字串類型會很低效,因此.NET基底類別庫提供了System.Text命名空間.在這個(相對較小的)命名空間中有一個叫StringBuilder的類.和System.String類相似,StringBuilder定義了很多用來替換或格式化片段的方法.如果我們希望在C#中使用這個類型,第一部就是匯入正確的命名空間:

// StringBuilder lives here!using System.Text;

StringBuilder的獨特之處在於,當我們調用這個類型成員時,都是直接修改對象內部的字元資料(因此更高效),而不是擷取按修改後格式的資料副本.當建立StringBuilder執行個體時,可以通過其中一個建構函式來提供對象的初始值.

 

As you can see, we are appending to the internal buffer, and are able to replace (or remove) characters at will. By default, a StringBuilder is only able to hold a string of 16 characters or less; however, this initial value can be changed via an additional constructor argument:

// Make a StringBuilder with an initial size of 256.StringBuilder sb = new StringBuilder("**** Fantastic Games ****", 256);

If you append more characters than the specified limit, the StringBuilder object will copy its

data into a new instance and grow the buffer by the specified limit.

(StringBuilder)可以看到,我們向內部緩衝區追加資料,並且可以隨意替換(或移除)字元.預設情況下,StringBuilder只能儲存16個字元以下的字串,然而,我們可以通過其他建構函式參數來改變這個初始值.

// Make a StringBuilder with an initial size of 256.StringBuilder sb = new StringBuilder("**** Fantastic Games ****", 256);

如果追加的字元數超過規定的限制,StringBuilder對象會將它的資料複製到新的執行個體中,並根據規定的限制來擴大緩衝區.

 

C# provides the checked keyword. When you wrap a statement (or a block of statements) within the scope of the checked keyword, the C# compiler emits additional CIL instructions that test for overflow conditions that may result when adding, multiplying, subtracting, or dividing two numerical data types.

If an overflow has occurred, you will receive a runtime exception (System.OverflowException to be exact). observe the following update:

static void ProcessBytes(){    byte b1 = 100;    byte b2 = 250;    // This time, tell the compiler to add CIL code    // to throw an exception if overflow/underflow    // takes place.    try    {        byte sum = checked((byte)Add(b1, b2));        Console.WriteLine("sum = {0}", sum);    }    catch (OverflowException ex)    {        Console.WriteLine(ex.Message);    }}

C#提供了checked關鍵字,當我們把一個語句(或者語句塊)封裝在checked關鍵字域內時,C#編譯器會使用額外的CIL指令來測試在將兩個數值資料類型相加,相乘,相減或者相除時可能產生的溢出情況.

如果發生了溢出,我們會得到一個運行時異常(System.OverflowException)看下面的代碼:

static void ProcessBytes(){    byte b1 = 100;    byte b2 = 250;    // 這次告訴編譯器增加CIL代碼,如果發生上溢或者下溢就拋出異常.    try    {        byte sum = checked((byte)Add(b1, b2));        Console.WriteLine("sum = {0}", sum);    }    catch (OverflowException ex)    {        Console.WriteLine(ex.Message);    }}

 

If you wish to force overflow checking to occur over a block of code statements, you can do so

by defining a checked scope as follows:

try{    checked    {        byte sum = (byte)Add(b1, b2);        Console.WriteLine("sum = {0}", sum);    }}catch (OverflowException ex){    Console.WriteLine(ex.Message);}

如果希望對一段代碼語句塊進行強制溢出檢測,可以按如下所示定義checked域:

try{    checked    {        byte sum = (byte)Add(b1, b2);        Console.WriteLine("sum = {0}", sum);    }}catch (OverflowException ex){    Console.WriteLine(ex.Message);}

 

So, to summarize the C# checked and unchecked keywords, remember that the default behavior of the .NET runtime is to ignore arithmetic overflow. When you want to selectively handle discrete statements, make use of the checked keyword. If you wish to trap overflow errors throughout your application, enable the /checked flag. Finally, the unchecked keyword may be used if you have a block of code where overflow is acceptable (and thus should not trigger a runtime exception).

現在總結一下C#的checked和unchecked關鍵字,記住.NET運行時的預設行為是忽略運算溢出.當我們需要有選擇地處理分散的語句時,可以使用checked關鍵字.如果希望在整個程式中捕捉溢出錯誤,可以啟用/checked標誌.最後,如果有一段代碼中的溢出是可以接受的(因此不應該發出運行時異常),可以使用unchecked關鍵字.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.