简体   繁体   中英

Overloads New Method With Args

I've been build a large application that requires the need to overload the NEW method with args (Common I guess).

I have lots of properties in some classes and most if not all get overloaded in the new method. I wondered if there is a way to capture the arguments from the method and assign the values to the custom object by looking through the properties/args. All my property name within the class match the ones being passed as args in the method so matching the "name" properties should be possible???

OR a less taxing way of manually typing me.property = arg for each and every argument...

for example:

public class myClass
    property arg1 as string
    property arg2 as string
    property arg3 as string

    public sub new(arg1 as string, arg2 as string, arg3 as string)
        For each arg in methodbase.getcurrentmethod.getParameters
            custObj(<property name>).value = arg.value where custObj.name = arg.name
        end for
    end sub
end class

This isn't valid VB.net syntax is just an example of what I'm trying to achieve.

There is no real solution to your problem because reflection can not get a parameters value. But:

You can hack your way around this by creating an anonymous type inside your method and taking advantage of projection initialisers. You can then interrogate the anonymous type's properties using reflection. https://stackoverflow.com/a/1868507/4035472

The result could be something like this:

Class [MyClass]
    Public Property arg1 As String
    Public Property arg2 As String
    Public Property arg3 As String

    Public Sub New(arg1 As String, arg2 As String, arg3 As String)

    Dim hack = New With { arg1, arg2, arg3}

    Dim all = BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic
    Dim props = GetType([MyClass]).GetProperties(all).ToDictionary(Function(x) x.Name, Function(x) x)

    For Each p As PropertyInfo In hack.GetType().GetProperties()
        props(p.Name).SetValue(Me, p.GetValue(hack))
    Next
    End Sub
End Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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