Dynamically invoke properties by string name using VB.NET

前端 未结 3 553
北海茫月
北海茫月 2020-12-28 14:30

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

Select Case oReader.Name
    Case \"NameExample1\"
        Me.Elements.NameE         


        
相关标签:
3条回答
  • 2020-12-28 15:07

    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.

    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".

    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.

    0 讨论(0)
  • 2020-12-28 15:14

    Yes, CallByName is the best solution for you. Here's instruction of doing it:

    CallByName(yourClassOrObjectName,"NameExample1",CallType.Set,oReader.ReadString)
    

    You can write "NameExample" in place of "NameExample1".
    Mention, that third parameter lets you 'Get', 'Let' that parameter (and even invoke any method).
    So you can get your parameter's value using CallType.Get.

    0 讨论(0)
  • 2020-12-28 15:19

    I can't believe the other posters told you to use reflection. VB as a CallByName function that does exactly what you want.

    0 讨论(0)
提交回复
热议问题