我有以下类属性:
[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;
例如:如果Wind = 3
, 至少会有 3 Enums.Effects.Low
在result
里面列表。
[AttributeUsage(AttributeTargets.Property)]
public sealed class EffectAspectAttribute : Attribute
{
public Enums.EffectsAspect { get; private set; }
public EffectAspectAttribute (Enums.EffectsAspect aspect)
{
this.Aspect = aspect;
}
}
问题是:int amount = (int)p.GetConstantValue();
抛出异常说:
Literal value was not found.
我找不到它的意思。
最佳答案
你可以尝试使用
p.GetValue(this, null)
代替
p.GetConstantValue();
您可以引用此链接主题:Difference between GetValue, GetConstantValue and GetRawConstantValue
关于C#通过属性获取字段值(PropertyInfo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38992425/