c#中as关键字的使用

来源:互联网 发布:淘宝上怎么延迟收货 编辑:程序博客网 时间:2024/05/14 02:16
现在我们猜猜看以下的类型转换是否成功(提示:从编译和运行时类型转换角度考虑)。object myFoo = container.Resolve<Foo>();   //获取未Foo1类型   try { Logger myFoo1 = (Logger)myFoo;   if (myFoo1 != null)   {   Console.WriteLine("Covert successful.");   }   }   catch   {   Console.WriteLine("Covert failed.");   } 相信聪明的大家已经想出答案了,激动人心的时刻到了现在让我们公布答案:转换失败抛出异常。
和强制转换不同,as转换不成功的话返回null,且不抛出异常;

此文章由人工翻译。 将光标移到文章的句子上,以查看原文。 更多信息。
译文 原文as(C# 参考)其他版本 可以使用 as 运算符执行转换的某些类型在兼容之间的引用类型或 可以为 null 的类型。 下面的代码提供了一个示例。C#   class csrefKeywordsOperators   {       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 变量只计算一次。expression is type ? (type)expression : (type)null请注意 as 运算符执行只引用转换、nullable 转换和装箱转换。 as 运算符不能执行其他转换,如用户定义的转换,应是通过使用转换的表达式。示例C#class ClassA { }class ClassB { }class MainClass{    static void Main()    {        object[] objArray = new object[6];        objArray[0] = new ClassA();        objArray[1] = new ClassB();        objArray[2] = "hello";        objArray[3] = 123;        objArray[4] = 123.4;        objArray[5] = null;        for (int i = 0; i < objArray.Length; ++i)        {            string s = objArray[i] as string;            Console.Write("{0}:", i);            if (s != null)            {                Console.WriteLine("'" + s + "'");            }            else            {                Console.WriteLine("not a string");            }        }    }}/*Output:0:not a string1:not a string2:'hello'3:not a string4:not a string5:not a string*/

0 0