码迷,mamicode.com
首页 > Windows程序 > 详细

C# Keywords - as

时间:2014-12-09 19:16:46      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:style   io   ar   color   os   使用   sp   for   strong   

记录一下在日常开发过程中遇到的一些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();

}
}

 

C# Keywords - as

标签:style   io   ar   color   os   使用   sp   for   strong   

原文地址:http://www.cnblogs.com/htwdz-qhm/p/4153890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!