C#按属性获取字段值(PropertyInfo)
我有以下类属性:C#按属性获取字段值(PropertyInfo),c#,attributes,C#,Attributes,我有以下类属性: [EffectAspect(Enums.Effects.Low)] public int Wind { set; get; } [EffectAspect(Enums.Effects.Low)] public int Fire { set; get; } [EffectAspect(Enums.Effects.Medium)] public int Water { get; set; } [EffectAspect(Enums.Effects.Huge)] public
[EffectAspect(Enums.Effects.Low)]
public int Wind { set; get; }
[EffectAspect(Enums.Effects.Low)]
public int Fire { set; get; }
[EffectAspect(Enums.Effects.Medium)]
public int Water { get; set; }
[EffectAspect(Enums.Effects.Huge)]
public int Earth { get; set; }`
现在,让我们假设我要计算总的低点、中间点和拥抱。
所以我写了这样的东西:
List<Enums.Effects> result = new List<Enums.Effects>();
PropertyInfo[] properties = GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
object[] attrs = p.GetCustomAttributes(true);
foreach (Object attr in attrs)
{
var effectAttr = attr as EffectAspect;
if (effectAttr != null)
{
int amount = (int)p.GetConstantValue();
for (int i = 0; i < amount; i++)
{
result.Add(effectAttr.Aspect);
}
}
}
}
return result;
问题是:intamount=(int)p.GetConstantValue()代码>抛出异常,表示:
找不到文本值
我找不到它的意思。您可以尝试使用
p.GetValue(this, null)
而不是
p.GetConstantValue();
您可以参考此链接线程:那么为什么要调用GetConstantValue
?“通过编译器返回与属性关联的文本值。”-在您的案例中没有这样的值。我怀疑您想要p.GetValue(this,null)
。我检查了这个GetValue方法,但是添加这些参数对我来说有点奇怪。无论如何,谢谢。我仍然很兴奋你真的帮助了我,你是我在这个论坛上的英雄:)
p.GetConstantValue();