我怎样才能获得自定义属性prop的值?

时间:2014-11-24 22:44:15

标签: c# asp.net-mvc reflection

我使用MVC和c#..我怎样才能获得财产的价值?

谢谢

foreach (var prop in this.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(CalcProgressAttribute))))
{

 //i need prop 's value here

}

1 个答案:

答案 0 :(得分:1)

试试这个,让GetProperty按预期工作:

foreach (var prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(prop => Attribute.IsDefined(prop, typeof(CalcProgressAttribute))))
{

 object value = prop.GetValue(this, null);

}

我不知道您的foreach循环是否有效,因为我无法证明您的代码的以下部分: .Where(prop => Attribute.IsDefined(prop, typeof(CalcProgressAttribute))))。但如果没有Where,循环将遍历所有属性。

相关问题