从反射与后期绑定中,什么应该更合适或建议在 VB.NET 中使用:
'Type can be various objects that have a common property for sure.'
Dim type = sender.GetType()
Dim prop = type.GetProperty("Text", 20)
Dim value = property.GetValue(sender, Nothing)
相对:
Dim value = sender.Text
从反射与后期绑定中,什么应该更合适或建议在 VB.NET 中使用:
'Type can be various objects that have a common property for sure.'
Dim type = sender.GetType()
Dim prop = type.GetProperty("Text", 20)
Dim value = property.GetValue(sender, Nothing)
相对:
Dim value = sender.Text
在幕后,他们都在做同样的事情(相对而言)。VB.NET 的后期绑定功能是在运行时通过程序集元数据查询完成的,这正是反射的全部意义所在。
第一种方法的好处之一是您有机会以更细粒度的方式处理错误。
如果您确实使用后期绑定,您可以将提取属性的方法放入具有 Option Explicit = Off 的部分类中。这样,您仍然可以在其余代码中进行类型检查。
sender.Text 不总是一个字符串吗?那么值的类型可以在编译时推断出来,让后者成为早期绑定的例子?