简体   繁体   中英

How to compare inherited type with Base Type?

I have one method as,

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

This method will be get called and can get passed the Page , UserControl , or any other type.

I want to check the type of incoming object, if it's Page , UserControl or other type.

But I was unable to do that. Whenever I tried using the GetType() of typeOf() on System.Web.UI.UserControl . It gives,

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

When I tried other methods like .IsAssignableFrom() and .IsSubclassOf() but I was still unable to do that.

One more note my incoming usercontrols or page can be multiple inherited from different controls/pages. So its immediate base type is not that of System.Web.UI.<Type> .

Let me know in case of any confusion. VB/C# any way would work for me.

UPDATE

I have tried like,

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

This gives me same issue as above,

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

Instead of

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

you have to use

// 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

Notice absence of getting object type. is does that for you under hoof.

You can check type with simple as/null check pattern:

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

it is more efficient (only single cast) than using is as you will probably do something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM