投射时为什么不能使用GetType? [英] Why can't you use GetType when casting?

查看:67
本文介绍了投射时为什么不能使用GetType?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个仍未解决的问题,它将使该问题更加清晰。

I asked a still unanswered question that will shed more light on this question.

为什么我不能这样做...

Why can't I do this...

_wizardDialog.UIRoot.Controls.Clear()
_wizardDialog.UIRoot.Controls.Add(TryCast(wizardUserControl, wizardUserControl.GetType))

为什么以这种方式使用GetType会失败。尝试强制转换的参数是对象和类型。由于wizardUserControl.GetType返回一个类型,因此这是不合法的。 Visual Studio抱怨没有定义wizardUserControl.GetType。

Why does using GetType in this way fail. The argument for try cast are object and type. Since wizardUserControl.GetType returns a type how come this is not legal. Visual Studio is complaining wizardUserControl.GetType is not defined.

最重要的是,如何让WizardUserControl返回传递给我的方法的类型。这里调用的方法不必必须具有硬编码的类型...这就是所有这些OOP内容的重点...对吗?那你该怎么做。

The bottom line is how can I get WizardUserControl to return the type that is being passed in to my method. The method that is being called into here should not have to have the type hard-coded...that's the point of all of this OOP stuff...right? So how do you do this.

请阅读其他问题,如果可以的话,在那儿回答...这就是我要解决的问题。

Please read the other question and answer there if you can...that is the problem I am tyring to solve.

我正在学习哎呀东西。

Seth

推荐答案

以这种方式思考:


  • GetType()是功能。它返回一个对象。

  • GetType() is a function. It returns an Object.


  • 您不知道类型是什么,或者您不需要询问:)

在投射对象时,您告诉编译器的类型是什么。

When you are casting an object, you are telling the COMPILER what it's type is.

您不能同时询问类型是什么,它在 runtime 发生,并告诉编译器在编译时是什么,在同一位置。

You can't both ask a type what it is, which happens at runtime, and tell the compiler what it is at compile time, in the same place.

我想您也可以将诸如GetType(String)之类的内容视为关键字。在此示例中更清楚:

I guess you can also think of something like GetType(String) as a keyword. It is clearer in this example:

  // Makes sense, we tell the compiler what the object is.  We could still get a 
  // *runtime* exception, if we were lying to the compiler.
  Dim car = CType(vehicle, Car); 

  // this doesn't make sense, since we don't know what is in "anObj"
  Dim anObj As Object = "(I don't know what it is, thats why it's an object)"
  Dim car = ctype(anObj, anObj.GetType() )

  // and this is the clearest, in vb.  you can see the type is being used kinda like
  // a keyword.  it won't change, but a call to GetType could
  If TypeOf anObj is Car Then
   ...

在第二种情况下,您不知道 anObj是什么类型。自

In the second case, you don't know what type "anObj" is. Since

这篇关于投射时为什么不能使用GetType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆