zoukankan      html  css  js  c++  java
  • C#中的is和as

    需要检查一个实例的类型时,一般都使用强制转换操作:

    C# 代码
    bool CheckIsType(object source)
    ...{
    try
    ...{
    TagClass result
    = (TagClass)source;
    return true;
    }

    catch
    ...{
    return false;
    }

    }

    后来发现了object.GetType(),但是很难去判断实例的类型是否兼容。现在我向大家推荐is和as运算符.

    is 检查对象是否与给定类型兼容。

    as 运算符用于在兼容的引用类型之间执行转换。

    为什么推荐给各位:

    as 运算符类似于强制转换操作。如果无法进行转换, as 返回 null ,而强制转换会引发异常。

    有些情况下我们也只是想判断类型,没有必要去做转换,那么我们就可以用is了。

    以下是as的例子(代码引用自MSDN):

    C# 代码
    using System;
    class Class1
    ...{
    }


    class Class2
    ...{
    }


    class MainClass
    ...{
    static void Main()
    ...{
    object[] objArray = new object[6];
    objArray[
    0] = new Class1();
    objArray[
    1] = new Class2();
    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");
    }

    }

    }

    }



    以下是is的例子(代码引用自MSDN):

    using System;
    class Class1
    ...{
    }


    class Class2
    ...{
    }


    class IsTest
    ...{
    static void Test(object o)
    ...{
    Class1 a;
    Class2 b;

    if (o is Class1)
    ...{
    Console.WriteLine(
    "o is Class1");
    a
    = (Class1)o;
    // Do something with "a."
    }

    else if (o is Class2)
    ...{
    Console.WriteLine(
    "o is Class2");
    b
    = (Class2)o;
    // Do something with "b."
    }

    else
    ...{
    Console.WriteLine(
    "o is neither Class1 nor Class2.");
    }

    }

    static void Main()
    ...{
    Class1 c1
    = new Class1();
    Class2 c2
    = new Class2();
    Test(c1);
    Test(c2);
    Test(
    "a string");
    }

    }
  • 相关阅读:
    ZeptoLab Code Rush 2015
    UVa 10048 Audiophobia【Floyd】
    POJ 1847 Tram【Floyd】
    UVa 247 Calling Circles【传递闭包】
    UVa 1395 Slim Span【最小生成树】
    HDU 4006 The kth great number【优先队列】
    UVa 674 Coin Change【记忆化搜索】
    UVa 10285 Longest Run on a Snowboard【记忆化搜索】
    【NOIP2016提高A组模拟9.28】求导
    【NOIP2012模拟10.9】电费结算
  • 原文地址:https://www.cnblogs.com/leeolevis/p/1383130.html
Copyright © 2011-2022 走看看