System.Reflection.PropertyInfo getPropertyInfo(System.Type type,string NavigationPath)

时间:2012-06-26 18:22:52

标签: .net data-binding reflection

我需要一个具有以下签名的函数:

System.Reflection.PropertyInfo getPropertyInfo(System.Type type, string NavigationPath)

或在VB中:

Function GetPropertyInfo(Type As System.Type, NavigationPath As String) As System.Reflection.PropertyInfo

使用方法:

Dim MyPropertyInfo As PropertyInfo = GetPropertyInfo(GetType(Order),"Customer.Address.State.Code")
Dim DisplayName As String = MyStringFunctions.FriendlyName(MyPropertyInfo.Name)

它使用以句点分隔的路径导航。 我无法弄清楚如何利用数据绑定框架来做到这一点。 第一个障碍似乎只是想要使用对象(而不是类型), 第二个障碍是我甚至无法使用控制之外的对象。 我认为在某个地方数据绑定处理类型和属性类型;它必须!

谢谢!

2 个答案:

答案 0 :(得分:0)

对于数据绑定,您需要属性的值而不是属性本身(即返回object而不是PropertyInfo)。

This similar question提供了这样的实现,如果你真的希望方法返回属性而不是它的值,也可以很容易地修改它。

答案 1 :(得分:0)

这是我提出的,不使用绑定基础设施。 我仍然认为绑定会做得更好。

  Function GetPropertyInfo(Type As System.Type, NavigationPath As String) As System.Reflection.PropertyInfo
    For Each Part As String In NavigationPath.Split(".")
      GetPropertyInfo = Type.GetProperty(Part)
      If GetPropertyInfo IsNot Nothing Then
        Type = GetPropertyInfo.PropertyType
      End If
    Next
  End Function
相关问题