使用VB.NET通过字符串名称动态调用属性 [英] Dynamically invoke properties by string name using VB.NET

查看:236
本文介绍了使用VB.NET通过字符串名称动态调用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在一个项目中,一段代码看起来像这样:

I'm currently working on a project where a section of the code looks like this:

Select Case oReader.Name
    Case "NameExample1"
        Me.Elements.NameExample1.Value = oReader.ReadString
    ....
    Case "NameExampleN"
        Me.Elements.NameExampleN.Value = oReader.ReadString
    ....
End Select

它持续一段时间.该代码显然很冗长,并且感觉好像可以改进.有什么方法可以在VB.NET中动态调用属性,以便可以执行以下操作:

It continues on for a while. The code is obviously verbose and it feels like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done:

Dim sReadString As String = oReader.ReadString
Me.Elements.InvokeProperty(sReadString).Value = sReadString

推荐答案

其他人的回答很合理,但是如果这是对性能敏感的代码,则可能需要将反射调用编译为委托.

Others have answered perfectly reasonably, but just in case this is a performance-sensitive piece of code, you might want to compile the reflective calls into delegates.

我有一个博客条目关于打开 MethodBase.Invoke >进入代表.该代码使用C#,但是相同的技术也可以应用于VB.NET.若要将此属性与属性一起使用,请使用

I've got a blog entry about turning MethodBase.Invoke into delegates. The code is in C#, but the same technique can be applied to VB.NET as well. To use this with properties, get the appropriate "setter" method with PropertyInfo.GetSetMethod and then build a delegate which invokes that. You could have a map from field name to "delegate to call to set the field".

只需重申一下,只有在性能关键的一段代码中,这才是真正必要的.否则,您可能仍然想创建一个Dictionary<string, PropertyInfo>以避免多次调用GetProperty,但是将其转换为委托的步骤可能不值得担心.

Just to reiterate, this is only really necessary if it's in a performance-critical piece of code. Otherwise, you might still want to create a Dictionary<string, PropertyInfo> to avoid calling GetProperty many times, but the step to convert it into a delegate probably isn't worth worrying about.

这篇关于使用VB.NET通过字符串名称动态调用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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