as C#

可以使用 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());
               }

           }
       }
   }

Tip:

as 运算符类似于强制转换操作。 但是,因此,如果转换是不可能的,as 返回 null 而不引发异常。

发布了42 篇原创文章 · 获赞 23 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/gaojinjingg/article/details/100705956
C#