as(C# 参考)

原文地址:https://msdn.microsoft.com/zh-cn/library/cscsdfbt(v=vs.110).aspx

可以使用 as 运算符执行转换的某些类型在兼容之间的引用类型或 可以为 null 的类型 下面的代码提供了一个示例。

 
   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 运算符不能执行其他转换,如用户定义的转换,应是通过使用转换的表达式。

示例
 
 
 
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 string
1:not a string
2:'hello'
3:not a string
4:not a string
5:not a string
*/

原文地址:https://www.cnblogs.com/Arlar/p/6030237.html