User u = new User();
Type t = typeof(User);
u is User -> returns true
u is t -> compilation error
この方法で、ある変数が何らかのタイプであるかどうかをテストするにはどうすればよいですか?
User u = new User();
Type t = typeof(User);
u is User -> returns true
u is t -> compilation error
この方法で、ある変数が何らかのタイプであるかどうかをテストするにはどうすればよいですか?
他の回答はすべて重要な省略が含まれています。
is
演算子は、オペランドの実行時タイプが正確に指定されたタイプであるかどうかをチェックしません。むしろ、ランタイムタイプが指定されたタイプと互換性があるかどうかを確認します。
class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.
ただし、互換性ではなく、IDのリフレクションチェックを使用してタイプIDをチェックします
bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal
or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an
それがあなたが望むものではない場合、あなたはおそらくIsAssignableFromが欲しいでしょう:
bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.
or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A
GetType()
基本タイプで定義されているため、すべての単一フレームワークタイプに存在しobject
ます。したがって、タイプ自体に関係なく、それを使用して基になるものを返すことができますType
だから、あなたがする必要があるのは:
u.GetType() == t
インスタンスのタイプがクラスのタイプと等しいかどうかを確認する必要があります。インスタンスのタイプを取得するには、次のGetType()
メソッドを使用します。
u.GetType().Equals(t);
また
u.GetType.Equals(typeof(User));
それをする必要があります。もちろん、必要に応じて「==」を使用して比較を行うこともできます。
オブジェクトが特定の型変数と互換性があるかどうかを確認するために、
u is t
あなたは書くべきです
typeof(t).IsInstanceOfType(u)