使用此命令检查c是否是TForm的实例。

c.GetType().Name.CompareTo("TForm") == 0

除了使用字符串作为CompareTo()的参数之外,还有更类型安全的方法吗?


当前回答

bool isValid = c.GetType() == typeof(TForm) ? true : false;

或者更简单的

bool isValid = c.GetType() == typeof(TForm);

其他回答

if(c is TFrom)
{
   // Do Stuff
}

或者如果你计划使用c作为一个TForm,使用下面的例子:

var tForm = c as TForm;
if(tForm != null)
{
   // c is of type TForm
}

第二个示例只需要检查一次c是否为TForm类型。如果你检查c是否为TForm类型,然后强制转换它,CLR会进行额外的检查。 这是参考资料。

编辑:从乔恩·斯基特那里偷来的

如果你想确保c是TForm的,而不是任何从TForm继承的类,那么使用

if(c.GetType() == typeof(TForm))
{
   // Do stuff cause c is of type TForm and nothing else
}

Or

c.getType() == typeOf(TForm)

而且,在某种程度上也是一样的

Type.IsAssignableFrom(Type c)

如果c和当前Type表示相同类型,则为 current Type在c的继承层次结构中,或者如果current Type是c实现的接口,或者如果c是泛型类型 参数,当前类型表示c的约束之一。”

网址:http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

正如其他人提到的,“is”关键字。但是,如果您稍后要将其转换为该类型,例如。

TForm t = (TForm)c;

然后你应该使用“as”关键字。

例如,TForm t = c作为TForm。

然后你可以检查

if(t != null)
{
 // put TForm specific stuff here
}

不要和is合并,因为这是一张重复的支票。

bool isValid = c.GetType() == typeof(TForm) ? true : false;

或者更简单的

bool isValid = c.GetType() == typeof(TForm);