zoukankan      html  css  js  c++  java
  • C#探秘系列(二)

    深入类之前的准备

    在讨论C#的类之前,有必要对C#中不同于C++的迷人的新特性作一总结,这对之后的学习大有裨益。

    一、Switch语句

    使用switch语句有三点需要注意,其中1、3点为新特性:

    1.现在在执行一条case语句后,程序流不能跳至下一case语句中,而在C++中可以。如:

    int var = 100;
    switch (var) 
    { 
        case 100: Console.WriteLine("<Value is 100>"); // 这里没有 break 
        case 200: Console.WriteLine("<Value is 200>"); break; 
    }

    在C++中的输出为

    <Value is 100><Value is 200>

    而在C#中,你将得到一个编译错误:

    error CS0163: Control cannot fall through 
           from one case label ('case 100:') to another

    如果你想要从”case 100”跳到”case 200”, 就必须用goto语句显示地跳转:

    int var = 100;
    switch (var) 
    { 
        case 100: Console.WriteLine("<Value is 100>");
        goto case 200;
        case 200: Console.WriteLine("<Value is 200>"); break; 
    }
    

    2、但你可以像C++中这样用:

    switch (var) 
    {
        case 100: 
        case 200: Console.WriteLine("100 or 200<VALUE is 200>"); break; 
    }

    3、C#允许字符串匹配case

    const string WeekEnd = "Sunday";
    const string WeekDay1 = "Monday";
    
    //....
    
    string WeekDay = Console.ReadLine();
    switch (WeekDay ) 
    { 
    case WeekEnd: Console.WriteLine("It's weekend!!"); break; 
    case WeekDay1: Console.WriteLine("It's Monday"); break;
    
    }

    二、foreach语句

    新版的Java也引入foreach语句,foreach可以避免引起越界的问题,同时简化代码,而可读性又不会降低,可谓一箭三雕:

    static void Main( string[] args )
    {
    foreach (String s in args)
    {
    Console.WriteLine( "The consloe arguments are: {0}", s );
    }
    }

    预处理命令#region

    预处理指令#region可以通过一条注释标记一段代码文本。其主要用途是使Visual Studio 这样的工具可以标记一个代码区域,在编辑器中将该区域折起来,只显示区域的注释。
    在用C#编程时,我们经常会用#region将using 语句的代码区折叠起来,如:

    #region Using directives
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    #endregion

    以上基本上是进入类话题中必备的知识点了,当然还有一些较为生僻的用法,咱们会在后面即用即谈。

  • 相关阅读:
    C# 反射修改私有静态成员变量
    symfony2 controller
    symfony2 路由工作原理及配置
    symfony2 安装并创建第一个页面
    git操作命令
    Node异步I/O、事件驱动与高性能服务器
    nodejs get/request
    nodejs events模块
    nodejs 小爬虫
    nodejs API
  • 原文地址:https://www.cnblogs.com/jscitlearningshare/p/4357514.html
Copyright © 2011-2022 走看看