【问题标题】:Overloads New Method With Args使用 Args 重载新方法
【发布时间】:2015-12-04 03:25:28
【问题描述】:

我一直在构建一个大型应用程序,需要使用 args 重载 NEW 方法(我猜很常见)。

我在某些类中有很多属性,而且大多数(如果不是全部)在新方法中都被重载了。我想知道是否有办法从方法中捕获参数并通过查看属性/参数将值分配给自定义对象。我在类中的所有属性名称都与方法中作为参数传递的名称匹配,因此应该可以匹配“名称”属性???

或者为每个参数手动输入me.property = arg 的一种不那么费力的方式...

例如:

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

这不是有效的 VB.net 语法只是我试图实现的一个示例。

【问题讨论】:

    标签: vb.net methods reflection


    【解决方案1】:

    您的问题没有真正的解决方案,因为反射无法获得参数值。但是:

    你可以通过在里面创建一个匿名类型来解决这个问题 您的方法并利用投影初始化程序。你可以 然后使用反射询问匿名类型的属性。 https://stackoverflow.com/a/1868507/4035472

    结果可能是这样的:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多