【问题标题】:How to compare inherited type with Base Type?如何比较继承类型和基本类型?
【发布时间】:2016-02-07 07:24:08
【问题描述】:

我有一种方法,

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(),但我仍然无法做到这一点。

另外请注意,我传入的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.

【问题讨论】:

  • 您可以使用is 检查类型,或者干脆尝试 使用as 进行转换,如果不是null - 那么您需要类型实例。
  • 我不想陷入try catch 铸造,这不是一个好习惯,我已经尝试过Is,但仍然是同样的问题
  • 在使用as/null check 时不需要try/catch。你能用is发布不工作的代码吗?

标签: c# vb.net reflection types


【解决方案1】:

代替

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();
    ...
}

【讨论】:

  • 当我执行 `If (incomingPage Is System.Web.UI.UserControl) Then` 时,它仍然给出错误 'UserControl' is a type in 'UI' and cannot be used as an expression.
  • 我的答案在C#。似乎在 vb.net Is is different 中,右侧表达式应该是一个对象。请参阅编辑(vb.net 部分,我正在尝试使用TypeOf)。
猜你喜欢
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多