次の方法で共有


パターン マッチングと is 演算子と as 演算子を使用して安全にキャストする方法

オブジェクトはポリモーフィックであるため、基底クラス型の変数で派生 を保持できます。 派生型のインスタンス メンバーにアクセスするには、値を派生型に キャスト し直す必要があります。 ただし、キャストでは、InvalidCastException がスローされるリスクが生まれます。 C# には、パターン マッチング ステートメントがあります。これは成功する場合のみという条件でキャストを実行します。 C# には、値が特定の型であるかどうかをテストする is 演算子と as 演算子も用意されています。

次の例は、パターン マッチング is ステートメントを使用する方法を示しています。

var g = new Giraffe();
var a = new Animal();
FeedMammals(g);
FeedMammals(a);
// Output:
// Eating.
// Animal is not a Mammal

SuperNova sn = new SuperNova();
TestForMammals(g);
TestForMammals(sn);
// Output:
// I am an animal.
// SuperNova is not a Mammal

static void FeedMammals(Animal a)
{
    if (a is Mammal m)
    {
        m.Eat();
    }
    else
    {
        // variable 'm' is not in scope here, and can't be used.
        Console.WriteLine($"{a.GetType().Name} is not a Mammal");
    }
}

static void TestForMammals(object o)
{
    // You also can use the as operator and test for null
    // before referencing the variable.
    var m = o as Mammal;
    if (m != null)
    {
        Console.WriteLine(m.ToString());
    }
    else
    {
        Console.WriteLine($"{o.GetType().Name} is not a Mammal");
    }
}

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 { }

前のサンプルは、パターン マッチング構文のいくつかの機能を示しています。 if (a is Mammal m) ステートメントは、テストと初期化割り当てを組み合わせたものになります。 割り当ては、テストが成功した場合にのみ発生します。 変数 m は、それが割り当てられている埋め込み if ステートメント内でのみスコープ内にあります。 同じメソッドで後で m にアクセスすることはできません。 前の例では、 as 演算子 を使用してオブジェクトを指定した型に変換する方法も示しています。

次の例に示すように、 null 許容値型に値 があるかどうかをテストするために同じ構文を使用することもできます。

int i = 5;
PatternMatchingNullable(i);

int? j = null;
PatternMatchingNullable(j);

double d = 9.78654;
PatternMatchingNullable(d);

PatternMatchingSwitch(i);
PatternMatchingSwitch(j);
PatternMatchingSwitch(d);

static void PatternMatchingNullable(ValueType? val)
{
    if (val is int j) // Nullable types are not allowed in patterns
    {
        Console.WriteLine(j);
    }
    else if (val is null) // If val is a nullable type with no value, this expression is true
    {
        Console.WriteLine("val is a nullable type with the null value");
    }
    else
    {
        Console.WriteLine("Could not convert " + val.ToString());
    }
}

static void PatternMatchingSwitch(ValueType? val)
{
    switch (val)
    {
        case int number:
            Console.WriteLine(number);
            break;
        case long number:
            Console.WriteLine(number);
            break;
        case decimal number:
            Console.WriteLine(number);
            break;
        case float number:
            Console.WriteLine(number);
            break;
        case double number:
            Console.WriteLine(number);
            break;
        case null:
            Console.WriteLine("val is a nullable type with the null value");
            break;
        default:
            Console.WriteLine("Could not convert " + val.ToString());
            break;
    }
}

上記のサンプルは、変換で使用するパターン マッチングの他の機能を示しています。 null値を確認することで、null パターンの変数をテストできます。 変数のランタイム値が nullされると、型をチェックする is ステートメントは常に falseを返します。 ステートメント is パターン マッチングでは、 int?Nullable<int>などの null 許容値型は許可されませんが、その他の値型をテストできます。 前の例の is パターンは、null 許容値型に限定されません。 これらのパターンを使用して、参照型の変数に値があるかどうか、または nullかどうかをテストすることもできます。

前のサンプルでは、変数がさまざまな型の 1 つである可能性がある switch ステートメントで型パターンを使用する方法も示しています。

変数が特定の型であるかどうかをテストし、それを新しい変数に割り当てない場合は、参照型と null 許容値型に対して is 演算子と as 演算子を使用できます。 次のコードは、パターン マッチングが導入される前に C# 言語の一部であった is ステートメントと as ステートメントを使用して、変数が特定の型であるかどうかをテストする方法を示しています。

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

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

// Use pattern matching to test for null
// before referencing the variable
UsePatternMatchingIs(g);

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

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

double d = 9.78654;
UseAsWithNullable(d);

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

static void UsePatternMatchingIs(Animal a)
{
    if (a is Mammal m)
    {
        m.Eat();
    }
}

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

static void UseAsWithNullable(System.ValueType val)
{
    int? j = val as int?;
    if (j is not null)
    {
        Console.WriteLine(j);
    }
    else
    {
        Console.WriteLine("Could not convert " + val.ToString());
    }
}
class Animal
{
    public void Eat() => Console.WriteLine("Eating.");
    public override string ToString() => "I am an animal.";
}
class Mammal : Animal { }
class Giraffe : Mammal { }

class SuperNova { }

このコードとパターン マッチング コードを比較するとわかるように、パターン マッチング構文では、テストと割り当てを 1 つのステートメントで組み合わせることで、より堅牢な機能が提供されます。 可能な限り、パターン マッチング構文を使用してください。