zoukankan      html  css  js  c++  java
  • C# 强制转型与as和is

    一、两个类型之间的强制转型依靠转型操作符(非继承关系)

     1     class FirstType
     2     {
     3         public string Name { get; set; }
     4     }
     5 
     6     class SecondType : FirstType
     7     {
     8         public string Name { get; set; }
     9 
    10         //转型操作符
    11         public static explicit operator SecondType(FirstType firstType)
    12         {
    13             SecondType secondType = new SecondType() { Name = "转型自:" + firstType.Name };
    14             return secondType;
    15         }
    16     }

    FirstType类转型为SecondType类要写转型操作符(转型操作符实际上就是一个方法,类型的转换需要手工写代码完成)。

    1  FirstType f = new FirstType() { Name = "First Type" };
    2  SecondType s = (SecondType)f;//转型成功
    3  //SecondType s1 = f as SecondType;//编译期转型失败,编译不通过

    二、有继承关系的类型转换用as关键字

    1 class FirstType
    2 {
    3         public string Name { get; set; }
    4 }
    5 
    6 class SecondType : FirstType
    7 {
    8 }
    1 SecondType s = new SecondType() { Name = "Second Type" };
    2 FirstType f1 = (FirstType)s;//强制转型
    3 FirstType f2 = s as FirstType;//as关键字

    强制转型和as都可以,但是从效率的角度来看,建议使用as。

    as不能操作基元类型,如果涉及基元类型的算法,需要通过is进行转型前判断类型,避免转型失败。

     1         static void Main(string[] args)
     2         {
     3             SecondType s = new SecondType() { Name = "Second Type"         
     4         };
     5             DoWithSomeType(s);
     6         }
     7         static void DoWithSomeType(object obj)
     8         {
     9             if (obj is SecondType)//判断类型
    10             {
    11                 SecondType s = obj as SecondType;
    12             }
    13         }

    参考:《编写高质量代码改善C#程序的157个建议》陆敏技

  • 相关阅读:
    Cobbler学习之一--Fedora17下配置Cobbler安装环境
    linux下 tar解压 gz解压 bz2等各种解压文件使用方法
    linux性能检测工具
    firefox的plugin-container进程关闭方法
    部署额外域控制器,Active Directory
    利用yum下载软件包的三种方法
    HP iLo2 试用序列号
    (转)Linux下root密码丢失和运行级别错误的解决办法
    linux下的5个查找命令
    (转)CentOs上配置samba服务
  • 原文地址:https://www.cnblogs.com/xuyouyou/p/13151009.html
Copyright © 2011-2022 走看看