다음을 통해 공유


방법: AS 및 IS 연산자를 사용한 안전한 캐스팅(C# 프로그래밍 가이드)

업데이트: 2008년 7월

개체는 다형성이므로 기본 클래스 형식의 변수는 파생 형식을 가질 수 있습니다. 파생 형식의 메서드에 액세스하려면 값을 파생 형식으로 다시 캐스팅해야 합니다. 그러나 이러한 경우 단순한 캐스팅을 시도하려면 InvalidCastException이 throw될 수 있는 위험을 감수해야 합니다. 이 때문에 C#은 isas 연산자를 제공합니다. 이러한 연산자를 사용하면 예외를 throw시키지 않고 캐스트 성공 여부를 테스트할 수 있습니다. 일반적으로 캐스트가 성공하면 실제로 캐스트 값을 반환하는 as 연산자가 훨씬 효율적입니다. is 연산자는 부울 값만 반환합니다. 따라서 이 연산자는 개체 형식을 결정하고 실제로 캐스트하지는 않는 경우에 사용할 수 있습니다.

예제

다음 예제에서는 예외가 throw될 위험 없이 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# 프로그래밍 가이드)

nullable 형식(C# 프로그래밍 가이드)

변경 기록

날짜

변경 내용

이유

2008년 7월

항목이 추가되었습니다.

콘텐츠 버그 수정