我将从用代码解释我的场景开始:
public class A { }
public class B : A { }
public class C : B { }
public class D { }
public class Test
{
private A a = new A ( ) ;
private B b = new B ( ) ;
private C c = new C ( ) ;
private D d = new D ( ) ;
public Test ( )
{
// Evaluates to "false"
if ( a.GetType == typeof(B) ) { } //TODO: Add Logic
// Evaluates to "true"
if ( b.GetType == typeof(B) ) { } //TODO: Add Logic
// I WANT this to evaluate to "true"
if ( c.GetType == typeof(B) ) { } //TODO: Add Logic
// Evaluates to "false"
if ( d.GetType == typeof(B) ) { } //TODO: Add Logic
}
}
这里要注意的重要一行是:
if ( c.GetType == typeof(B) ) { }
我相信这实际上会评估为“假”,因为 typeof(B) 和 typeof(C) 在两个方向上都不相等。 (C是B,但B不一定是C。)
但我需要的是某种将这一点考虑在内的条件。我如何判断一个对象是 B 还是从它派生的任何对象?
我不在乎它是否是从 B 派生的对象,只要基类 B 存在即可。而且我无法预料什么派生类可能会出现在我的应用程序中。我只需要假设将来可能存在未知的派生类——因此我只能专注于确保基类是我所期望的。
我需要一个条件来为我执行此检查。如何实现?
最佳答案
你可以只使用is
:
if (c is B) // Will be true
if (d is B) // Will be false
关于C#.NET - 如何让 typeof() 与继承一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1218178/