zoukankan      html  css  js  c++  java
  • Effective C# 学习笔记(三)在类型转换上多使用 as 和 is

    好处:使用 as is 在运行时判断类型转换是否成功,若是转换失败不会产生新的对象

    使用 as 转换对象类型,若是失败会返回 null ,这时只需判断是否为null就可判断是否转换成功,否则转换就是两步判断 1. 判断转换是否成功 2. 判断是否为null

    //使用 as

    object o = Factory.GetObject();

    // Version one:

    MyType t = o as MyType;

    if (t != null)

    {

    // work with t, it's a MyType.

    }

    else

    {

    // report the failure.

    }

     

    //强制转换

    object o = Factory.GetObject();

    // Version two:

    try

    {

    MyType t;

    t = (MyType)o;

    // work with T, it's a MyType.

    }

    catch (InvalidCastException)

    {

    // report the conversion failure.

    }

     

    限制:as不能用于原始类型,如: int double float and so on

     

    对于 foreach 这种 集合(所有实现了IEnumerable接口的类型)遍历操作中的类型转换的折中方案是使用 Cast<T>方法,其中T可为所有类型

    IEnumerable collection = new List<int>()

    {1,2,3,4,5,6,7,8,9,10};

    var small = from int item in collection

    where item < 5

    select item;

    var small2 = collection.Cast<int>().Where(item => item < 5).

    Select(n => n);

  • 相关阅读:
    Daemon——守护进程
    RTMP
    CR LF CR/LF
    SO_REUSEADDR
    [aac @ ...] more samples than frame size (avcodec_encode_audio2)
    前端向后端传数据的方法
    控制层接受参数
    Swagger2
    net.sf.json------json解析
    springboot
  • 原文地址:https://www.cnblogs.com/haokaibo/p/2096527.html
Copyright © 2011-2022 走看看