2015-01-12 34 views
5

我需要找到泛型類型內的屬性。這是一個古老的方式(和因爲我的代碼是專門用於WinRT的我相信我需要另一種方法):GetRuntimeProperties而不是GetProperty

PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetProperty(idField, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); 

我需要實現使用GetRuntimeProperties相同的結果。這是我的方法:

PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetRuntimeProperties().Single(p => p.Name.ToUpper() == idField.ToUpper()... 

,你可以看到我在自定義的方式來實現IgnoreCase,大概可以做的更好?
我該如何執行其餘的BindingFlags

謝謝!

回答

5

你其實不需要。這是怎麼Type.GetRuntimeTypes實現:

public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type) 
{ 
    CheckAndThrow(type); 

    IEnumerable<PropertyInfo> properties = type.GetProperties(everything); 
    return properties; 
} 

everything定義如下:

private const BindingFlags everything = BindingFlags.Instance | 
             BindingFlags.Public | 
             BindingFlags.NonPublic | 
             BindingFlags.Static; 

這意味着它已經尋找你所需要的標誌。

編輯:

如果要指定BindingFlags自己,你可以編寫自己的自定義擴展方法:

public static class TypeExtensions 
{ 
    public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo type, 
                  BindingFlags bindingFlags) 
    { 
     var propertyInfos = type.GetProperties(bindingFlags); 

     var subtype = type.BaseType; 
     if (subtype != null) 
      list.AddRange(subtype.GetTypeInfo().GetAllProperties(bindingFlags)); 

     return propertyInfos.ToArray(); 
    } 
} 

注意這尚未經過測試。這只是試圖告訴你,你可以自己做。

+0

1.您是如何弄清楚它是如何實現的? –

+0

2.如果我想更改一些'BindingFlags',該怎麼辦? –

+1

1.我添加了一個鏈接到我的文章(點擊'Type.GetRuntimeTypes')。 2.不幸的是,你不能。 –