2016-07-23 20 views
-1

我想創建一個擴展方法來列出lambda表達式中的屬性。C#列出lambda表達式中的類屬性

設說有一個名爲例

public class Example { 
    Public string Name {get;set;} 
    Public string Description {get;set;} 
} 

類擴展方法可以是類似下面

public static void GetProperties<T>(this T obj) where T : new() 
{ 

} 

預期使用:this.GetProperties<Example>(m=>m.

所以當i型米=>米。應顯示兩個屬性(名稱,說明)。

+1

這如何涉及到實體框架? – user3185569

回答

0

我認爲你需要使用FUNC:

public static void GetProperties<T, V>(this T obj, Func<T, V selector) where T : new() 
{ 

} 

用法:

Example ex = new Example(); 

ex.GetProperties(m => m.Name); // Func<Example, string> 
ex.GetProperties(m => m.Description); // Func<Example, string> 

我真的不明白裏面的方法預期的行爲。但你提到m.Namem.Description。所以一個屬性選擇器是你的方式。

Func<Example, string>是接受一個Example輸入參數並返回一個string(這在NameDescription情況下,屬性)的功能。

0
public static class PropertyUtility 
{ 
    public static string GetPropertyName<T>(this T entity, Expression<Func<T, object>> exp) 
    { 
     if (exp.Body is MemberExpression) { 
     return ((MemberExpression)exp.Body).Member.Name; 
    } 
    else { 
     var op = ((UnaryExpression)exp.Body).Operand; 
     return ((MemberExpression)op).Member.Name; 
    } 
    } 
} 

而且使用這樣的:

Example ex = new Example(); 
var property = ex.GetPropertyName(x => x.Description); 
+0

爲什麼我們需要使用'表達式',如果選擇器不被提供者使用,並且只是想在本地使用(在哪裏'Func'完全可以工作)? – user3185569

+0

這只是一個例子,有一個名爲'GetProperties'的想要的方法,最可能的就是它想要使用屬性名稱,而不是值。其他方面,爲什麼要將它作爲選擇器傳遞? 並且一個名爲'Get..'的方法應該返回somethig,對吧? – Nina