C#通过属性获取字段值(PropertyInfo)

标签 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 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.Lowresult里面列表。

[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/

相关文章:

c# - 调试本地 IIS Web 服务器上托管的 ASP.NET MVC3 应用程序

c# - 在 C# 中使用 IClassFactory 时出现 InvalidCastException

javascript - 面向对象的javascript : initialize an attribute with a self function call

c - 用 weak 属性在 c 中编写测试代码是不好的做法吗?

c# - Asp.net MVC - 如何在不知道这些角色的情况下获取用户角色?

javascript - 为什么 (file.lastModifiedDate == file.lastModifiedDate ) 在 JavaScript 中评估为 false?

C#用分钟限制小时

c# - 相当于 System::String::Format ("{0:D9}", x);

c# - 字符串拆分连续重复字符

javascript - 如何简化 Javascript 对象以便设置 obj.BG ='red' 而不是 obj.css ("style": "value")