型チェック: typeof、GetType、それともis? 質問する

型チェック: typeof、GetType、それともis? 質問する

多くの人が次のコードを使用しているのを見てきました。

Type t = typeof(SomeType);
if (t == typeof(int))
    // Some code here

しかし、次のようにすることもできると思います:

if (obj1.GetType() == typeof(int))
    // Some code here

あるいはこれ:

if (obj1 is int)
    // Some code here

個人的には最後のものが一番きれいだと感じますが、何か見落としているのでしょうか? どれを使うのが一番いいのでしょうか、それとも個人の好みの問題でしょうか?

ベストアンサー1

すべては異なります。

  • typeof型名(コンパイル時に指定)を受け取ります。
  • GetTypeインスタンスのランタイム タイプを取得します。
  • isインスタンスが継承ツリー内にある場合は true を返します。

class Animal { } 
class Dog : Animal { }

void PrintTypes(Animal a) { 
    Console.WriteLine(a.GetType() == typeof(Animal)); // false 
    Console.WriteLine(a is Animal);                   // true 
    Console.WriteLine(a.GetType() == typeof(Dog));    // true
    Console.WriteLine(a is Dog);                      // true 
}

Dog spot = new Dog(); 
PrintTypes(spot);

はどうですかtypeof(T)? これもコンパイル時に解決されますか?

はい。T は常に式の型です。ジェネリック メソッドは基本的に適切な型を持つ一連のメソッドであることを覚えておいてください。例:

string Foo<T>(T parameter) { return typeof(T).Name; }

Animal probably_a_dog = new Dog();
Dog    definitely_a_dog = new Dog();

Foo(probably_a_dog); // this calls Foo<Animal> and returns "Animal"
Foo<Animal>(probably_a_dog); // this is exactly the same as above
Foo<Dog>(probably_a_dog); // !!! This will not compile. The parameter expects a Dog, you cannot pass in an Animal.

Foo(definitely_a_dog); // this calls Foo<Dog> and returns "Dog"
Foo<Dog>(definitely_a_dog); // this is exactly the same as above.
Foo<Animal>(definitely_a_dog); // this calls Foo<Animal> and returns "Animal". 
Foo((Animal)definitely_a_dog); // this does the same as above, returns "Animal"

おすすめ記事