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

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

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


当前回答

Or

c.getType() == typeOf(TForm)

其他回答

试试下面的方法

if (c is 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
}

如果你想使用c作为TForm,它比其他答案更紧凑:

if(c is TForm form){
    form.DoStuff();
}

正如其他人提到的,“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);