2014-10-31 41 views
0

我目前正在建設一個以下列方式工作的流暢API:檢索的性能完整的命名空間中表達<Func<>引用>謂詞

this.Property(x => x.Address).Display("Postal Address"); 

因爲我需要在以後的日子引用這個數據,我會喜歡將它添加到字典中,其中密鑰的格式爲ClassName.PropertyName(這似乎是日後檢索數據的最可靠方法 - 儘管如果有更好的方法,我肯定會接受建議)。

舉例來說,如果我有一個類象下面這樣:

namespace ExampleProject.Demo.ViewModels 
{ 
    public class ExampleViewModel 
    { 
     public string Address { get; set; } 
    } 
} 

的地址屬性將是該命名空間後跟屬性名稱,像這樣的關鍵:ExampleProject.Demo.ViewModels.Address.ExampleViewModel

但是我很難通過從上面傳遞給Property(x => x)方法的表達式反射得到這個完整的信息。任何人都可以在正確的方向上指出我如何從Property方法的參數中檢索這些數據?

Property方法的簽名如下:

public PropertyInstance<TProp> Property<TProp>(Expression<Func<TModel, TProp>> expression) where TProp : class 
{ 
    ... 
} 

非常感謝

回答

4

下面將檢索的屬性:

var property = (PropertyInfo)(((MemberExpression)expression.Body).Member); 

這個,你可以檢索以下內容:

property.Name 
property.DeclaringType.FullName or AssemblyQualifiedName 

我寧可在您的密鑰中使用Type.AssemblyQualifiedName而不是名稱空間名稱,以防萬一您擁有包含相同類型的不同程序集。

+0

這就是我一直在尋找的謝謝你,並感謝你的'AssemblyQualifiedName'建議。 – 2014-10-31 14:11:29