如何比较继承类型和基本类型?

How to compare inherited type with Base Type?

我有一种方法,

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 可以从不同的 controls/pages 多重继承。所以它的直接基类型不是 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();
    ...
}