zoukankan      html  css  js  c++  java
  • C# Keywords

    记录一下在日常开发过程中遇到的一些C# 基础编程的知识!

    希望以后能用的着。知识是在平常的开发过程中去学到的。只有用到了,你才能深入的理解它,并用好它。

    本资料来源于:MSND

    下面是一些相关的code  和 说明。

    As 关键字 (属于运算符关键字)

    可以使用  as 运算符执行转换的某些类型 在兼容之间的引用类型 或可以为 null的类型。 这段话不好理解,说白了就是强制类型转换不会throw exception。 

            class Base

            {

                public override string ToString()

                {

                    return "Base";

                }

            }

            class Derived : Base

            {

            }

     class Program

            {

                static void Main()

                {

                  Derived d = new Derived();

                    Base b = d as Base;  // 引用类型的强制类型转换

                    if (b != null)

                    {

                        Console.WriteLine(b.ToString());

                    }

    }

     

     重点注意:

    As 运算符类似于强制类型转换操作,但是唯一不同的是,如果转换是不可能的,as会返回 null 而不引发异常。

    expression as type    这两给表达式的效果是一样的。

    Expression is type ? (type)expression : (type)null

    注意的是: as 运算符执行只引用转换、nullable 转换和装箱转换。 as 运算符不能执行其他转换,如用户定义的转换,应是通过使用转换的表达式。


    class ClassA { }
    class ClassB { }

    class Program

    {

    static void Main()
    {
    object[] obj = new object[6];
    obj[0] = new ClassA();
    obj[1] = new ClassB();
    obj[2] = "Hello";
    obj[3] = 100;
    obj[4] = 365.23;
    obj[5] = null;

    foreach (var val in obj)
    {
    string str = val as string; // 如果此刻类型转换失败,不会抛异常,而是赋空引用 null
    if (str != null)
    {
             Console.WriteLine("string: " + str);
    }
    else
    {
           Console.WriteLine(val + " not string type");
    }
    }
               Console.ReadLine();

    }
    }

  • 相关阅读:
    《剑指offer》第三十五题(复杂链表的复制)
    《剑指offer》第三十四题(二叉树中和为某一值的路径)
    分支限界法
    回溯法小实例
    BUFSIZ解析
    ofstream和ifstream详细用法
    回溯法——最大团问题(Maximum Clique Problem, MCP)
    位运算应用之二——大小写转换
    回溯法——n后问题
    回溯法——批处理作业调度
  • 原文地址:https://www.cnblogs.com/htwdz-qhm/p/4153890.html
Copyright © 2011-2022 走看看