简体   繁体   English

来自多个句柄的Sender.Gettype

[英]Sender.Gettype from multiple handles

I have code that handles multiple events. 我有处理多个事件的代码。 FYI - I use Devexpress Components. 仅供参考-我使用Devexpress组件。 I have two items, a Lookupedit and a GridLookupEdit, that are handled by the same code. 我有两个项目,一个Lookupedit和一个GridLookupEdit,由相同的代码处理。 I am trying to do something like the following: 我正在尝试执行以下操作:

    Dim type = sender.GetType()

    Select Case DirectCast(sender, Type).Name
        Case "mgrLUE"
            log("View metrics for manager: " & mgrLUE.Properties.GetDisplayText(mgrLUE.EditValue), Me.Name)
        Case "sectLUE"
            log("View metrics for section: " & sectGLUE.Properties.GetDisplayText(sectGLUE.EditValue), Me.Name)
    End Select

I am getting errors at the select case line. 在选择案例行时出现错误。 I cant figure out how to dynamically get the type to be able to direct cast to it. 我无法弄清楚如何动态获取类型以将其直接转换为它。 The types will be DevExpress.XtraEditors.GridLookUpEdit and DevExpress.XtraEditors.LookUpEdit in this case. 在这种情况下,类型将为DevExpress.XtraEditors.GridLookUpEdit和DevExpress.XtraEditors.LookUpEdit。 I have tried searching for a solution, but everything I have tried is failing. 我已经尝试寻找解决方案,但是我尝试的所有方法都失败了。

Thank you for the help. 感谢您的帮助。

Casting can't be done dynamically because its sole purpose is to let the compiler know that you expect an object to be of a certain type. 强制转换不能动态完成,因为它的唯一目的是让编译器知道您期望某个对象属于某种类型。 This is necessary so that the compiler knows what members the object contains when you try to access it. 这是必要的,以便编译器在您尝试访问该对象时知道该对象包含哪些成员。

I should mention that VB.NET has a feature called late binding , which allows you to access members of a type wrapped in an Object by looking up if the member you're trying to access exists at runtime. 我应该提到,VB.NET具有称为后期绑定的功能,该功能允许您通过查找要访问的成员在运行时是否存在来访问包装在Object中的类型的成员。 Using late binding, however, is not recommended as it is very easy to make mistakes and break your code. 但是, 建议使用后期绑定,因为这样很容易出错并破坏代码。

Now, as for your problem: Casting can be done if an object is of a certain type, or if it inherits from that type. 现在,针对您的问题:如果对象属于某种类型,或者它继承自该类型,则可以进行转换。 Since I'm guessing what you're using are controls (that you've placed on your form) they all should inherit from System.Windows.Forms.Control , thus you can cast them to that which contains the base property Name : 由于我猜您正在使用的是控件(已放置在窗体上),它们都应该继承自System.Windows.Forms.Control ,因此您可以将它们转换为包含基本属性Name控件:

Select Case DirectCast(sender, Control).Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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