[英]How to compare inherited type with Base Type?
我有一种方法,
public function DoSomethingGenricWithUIControls(ByVal incomingData As Object)
//Fun Stuff
End Function
该方法将被调用并可以传递Page
, UserControl
或任何其他类型。
我想检查传入对象的类型,如果它是Page
, UserControl
或其他类型。
但是我做不到。 每当我尝试在System.Web.UI.UserControl
上使用typeOf()
的GetType()
时。 它给,
'UserControl' is a type in 'UI' and cannot be used as an expression.
当我尝试其他方法,例如.IsAssignableFrom()
和.IsSubclassOf()
,我仍然无法做到这一点。
还有一点需要注意,我传入的usercontrols
或page
可以是多个从不同控件/页面继承的。 因此,它的直接基本类型不是System.Web.UI.<Type>
。
如有任何疑问,请通知我。 VB / C#可以为我工作。
UPDATE
我尝试过
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();
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.