[英]Get values of all string properties in current class instance
I'd like to implement a public getter which will get values of all string properties in current class instance and return it as concatinated string. 我想实现一个公共获取器,该获取器将获取当前类实例中所有字符串属性的值,并将其作为隐含字符串返回。
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; }
}
When I run this I get StackOverflowException.. 当我运行它时,我得到StackOverflowException。
That's because you end up querying AllProperties
recursively. 那是因为您最终
AllProperties
递归查询AllProperties
。
And .Where(property => property.Name != "AllProperties")
after GetProperties ()
to exclude it. 并在
GetProperties ()
之后加上.Where(property => property.Name != "AllProperties")
GetProperties ()
以排除它。
So it looks like this: 所以看起来像这样:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.