zoukankan      html  css  js  c++  java
  • C# 核心编程结构Ⅰ 笔记

    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关键字.

  • 相关阅读:
    Windows下的SASS环境搭建
    cocos开发环境搭建
    cocos2d-x中描述精灵帧图片的plist和json文件各个key的含义
    seajs模块路径解析 简单总结
    【LESS系列】内置函数说明
    Zepto自定义模块打包构建
    【LESS系列】高级特性
    【LESS系列】三角形Mixins
    关于delete和对象复制
    vue使用技巧
  • 原文地址:https://www.cnblogs.com/tangzhengyue/p/2508981.html
Copyright © 2011-2022 走看看