如何将继承类型与基本类型进行比较

本文关键字:类型 比较 继承 | 更新日期: 2023-09-27 18:20:58

我有一个方法,

public function DoSomethingGenricWithUIControls(ByVal incomingData As Object)
     //Fun Stuff
End Function

此方法将被调用,并且可以被传递PageUserControl或任何其他类型。

我想检查传入对象的类型,如果是PageUserControl或其他类型。

但我没能做到。每当我尝试在System.Web.UI.UserControl上使用typeOf()GetType()时。它给出了

'UserControl' is a type in 'UI' and cannot be used as an expression.

当我尝试其他方法,如.IsAssignableFrom().IsSubclassOf()时,我仍然无法做到这一点。

请注意,我传入的usercontrolspage可以是从不同控件/页面继承的多个。所以它的直接基类型不是System.Web.UI.<Type>的直接基。

如果有任何困惑,请告诉我。VB/C#任何方式都适用于我。

更新

我试过了,

 if( ncomingPage.GetType() Is System.Web.UI.UserControl)

这给了我和上面一样的问题,

'UserControl' is a type in 'UI' and cannot be used as an expression.

如何将继承类型与基本类型进行比较

而不是

if( ncomingPage.GetType() is System.Web.UI.UserControl)

你必须使用

// c#
if( ncomingPage is System.Web.UI.UserControl)
// vb.net fist line of code in my life ever! hopefully will compile
If TypeOf ncomingPage Is System.Web.UI.UserControl Then

请注意没有获取对象类型。is在蹄下为你做那件事。

您可以使用简单的as/null检查模式检查类型:

var page = ncomgingPage as UserControl;
if(page != null)
{
    ... // ncomingPage is inherited from UserControl
}

它比使用is更有效(只有单次投射),因为你可能会做一些类似的事情

// checking type
if( ncomingPage is System.Web.UI.UserControl)
{
    // casting
    ((UserControl)ncomingPage).SomeMethod();
    ...
}