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个建议》陆敏技

  • 相关阅读:
    Codeforces Round #384 (Div. 2)
    Codeforces Round #383 (Div. 2)
    bzoj-4514(网络流)
    bzoj-4518 4518: [Sdoi2016]征途(斜率优化dp)
    bzoj-1096 1096: [ZJOI2007]仓库建设(斜率优化dp)
    hdu-5988 Coding Contest(费用流)
    hdu-5992 Finding Hotels(kd-tree)
    用链表实现杭电1276士兵队列训练问题
    循环链表
    图书管理系统
  • 原文地址:https://www.cnblogs.com/xuyouyou/p/13151009.html
Copyright © 2011-2022 走看看