2016-03-15 25 views
0

我想實現一個公共getter,它將獲取當前類實例中所有字符串屬性的值並將其作爲concatinated字符串返回。獲取當前類實例中所有字符串屬性的值

public class BaseViewModel 
    { 
     public string AllProperties => GetType().GetProperties().Aggregate(string.Empty, (current, prop) => prop.PropertyType == typeof(string) ? current + (string)prop.GetValue(this, null) : current); 
    } 

public class ChildViewModel : BaseViewModel 
{ 
    public string prop1 { get; set; } 
    public string prop2 { get; set; } 
} 

當我運行此我得到StackOverflowException ..

+0

你也可以使用string.Concat:。string.Concat(的GetType()的GetProperties()式(丙=> prop.PropertyType == typeof運算(字符串) && prop.Name!= nameof(AllProperties))。Select(property =>(string)property.GetValue(this,null)) –

回答

2

那是因爲你最終查詢AllProperties遞歸。

.Where(property => property.Name != "AllProperties")GetProperties()之後排除它。

所以它看起來像這樣:

public string AllProperties => GetType().GetProperties(). 
    Where(property => property.Name != "AllProperties"). 
    Aggregate(string.Empty, (current, prop) => prop.PropertyType == typeof(string) ? current + (string)prop.GetValue(this, null) : current); 
+0

看起來我需要更多的咖啡..非常感謝! – larnacoeur

相關問題