方法: as 演算子と is 演算子を使用して安全にキャストする (C# プログラミング ガイド)

オブジェクトはポリモーフィックであるため、基本クラス型の変数のための派生型を保持できます。 派生型のメソッドにアクセスするには、値をキャストしてその派生型に戻す必要があります。 ただし、このような場合に単純にキャストを実行すると、InvalidCastException がスローされる危険性があります。 このため、C# には、is 演算子と as 演算子が用意されています。 これらの演算子を使用すると、例外がスローされることなくキャストが成功するかどうかをテストできます。 通常、as 演算子のほうが、キャストが正しく実行できる場合に、キャスト値を実際に返すのでより効率的です。 is 演算子は、ブール値のみ返します。 したがって、オブジェクトの型の確認のみ行い、キャストは行う必要がない場合に使用できます。

使用例

is 演算子および as 演算子を使用して、例外がスローされる危険性を回避しながら、参照型を別の参照型にキャストする方法を次の例に示します。 この例では、null 許容型に対し as 演算子を使用する方法も示します。

class SafeCasting
{
    class Animal
    {
        public void Eat() { Console.WriteLine("Eating."); }
        public override string ToString()
        {
            return "I am an animal.";
        }
    }
    class Mammal : Animal { }
    class Giraffe : Mammal { }

    class SuperNova { }

    static void Main()
    {
        SafeCasting app = new SafeCasting();

        // Use the is operator to verify the type.
        // before performing a cast.
        Giraffe g = new Giraffe();
        app.UseIsOperator(g);

        // Use the as operator and test for null
        // before referencing the variable.
        app.UseAsOperator(g);

        // Use the as operator to test
        // an incompatible type.
        SuperNova sn = new SuperNova();
        app.UseAsOperator(sn);

        // Use the as operator with a value type.
        // Note the implicit conversion to int? in 
        // the method body.
        int i = 5;
        app.UseAsWithNullable(i);


        double d = 9.78654;
        app.UseAsWithNullable(d);

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }

    void UseIsOperator(Animal a)
    {
        if (a is Mammal)
        {
            Mammal m = (Mammal)a;
            m.Eat();
        }
    }

    void UseAsOperator(object o)
    {
        Mammal m = o as Mammal;
        if (m != null)
        {
            Console.WriteLine(m.ToString());
        }
        else
        {
            Console.WriteLine("{0} is not a Mammal", o.GetType().Name);
        }
    }

    void UseAsWithNullable(System.ValueType val)
    {
        int? j = val as int?;
        if (j != null)
        {
            Console.WriteLine(j);
        }
        else
        {
            Console.WriteLine("Could not convert " + val.ToString());
        }
    }
}

参照

参照

型 (C# プログラミング ガイド)

キャストと型変換 (C# プログラミング ガイド)

null 許容型 (C# プログラミング ガイド)