vb.net 反射与后期绑定?
从反射与后期绑定来看,什么应该更合适,或者建议在 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
What should be more proper or what is recommended to use in VB.NET from either reflection vs. late binding:
'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)
versus:
Dim value = sender.Text
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在幕后他们都在做同样的事情(相对而言)。 VB.NET 的后期绑定功能是通过运行时的程序集元数据查询来完成的,这正是反射的全部内容。
第一种方法的好处之一是您有机会以更细粒度的方式处理错误。
Under the covers they are both doing the same thing (relatively speaking). VB.NET's late-binding feature is done via assembly metadata queries at runtime which is exactly what reflection is all about.
One of the benefits to your first approach is that you have an opportunity to handle errors in a more finely-grained manner.
sender.Text 不总是一个字符串吗?那么值的类型可以在编译时推断出来,使后者成为早期绑定的一个例子?
Isn't sender.Text always a string though? So the type of value can be inferred at compile time, making the latter an example of early binding?
如果您确实使用后期绑定,则可以将提取属性的方法放入带有 Option Explicit = Off 的分部类中。这样,您仍然可以对代码的其余部分进行类型检查。
If you do use late binding, you can put the method that extracts the properties into a partial class with Option Explicit = Off. That way, you still have type checking in the rest of your code.