c# - 列出具有特定属性的字段

标签 c# reflection

我正在尝试列出具有特定属性的所有字段,但仍然不太明白 GetValue() 需要什么样的对象。

[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
class SerializedAttribute : Attribute
{

}

class Program
{
    [Serialized] public Single AFloat = 100.0f;
    [Serialized] public Single AnotherFloat = 125.5f;
    [Serialized] public Single OnceAgain = 75.0f;

    static void Main(string[] args)
    {

        foreach(FieldInfo field in typeof(Program).GetFields())
        {
            foreach(Attribute attr in field.GetCustomAttributes())
            {
                if (attr is SerializedAttribute)
                {
                    Console.WriteLine("\t" + "Variable name: " + field.Name + "\t" + "Variable value:" + field.GetValue(/*"??????????????"*/));           
                }
            }
        }

        Console.ReadKey();

    }
}

我尝试了几次谷歌搜索,但显然我不太擅长解决问题。

最佳答案

GetValue 需要 Program 的实例

var program = new Program();
foreach (FieldInfo field in typeof(Program).GetFields())
{
    foreach (Attribute attr in field.GetCustomAttributes())
    {
        if (attr is SerializedAttribute)
        {
            Console.WriteLine("\t" + "Variable name: " + field.Name + 
                "\t" + "Variable value:" + field.GetValue(program));
        }
    }
}

也许您的意思是使这些属性静态,在这种情况下,您可以将null 传递给GetValue。尽管您正在寻找 SerializedAttribute,但情况似乎并非如此。

关于c# - 列出具有特定属性的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52080395/

相关文章:

c# - 是 Controller 异步中的后台 worker 吗?

go - 如何通过反射在GO中获取结构字段的地址

c# - 是否可以在 C# 中向现有模块添加类型?

c# - 在 Jquery 中使用 c# 变量

c# - 如何使用 .skip(i).take(j) 使用 lambda 表达式导航从数据库中获取给定范围的数据行

c# - 获得对 "fall through"面板的点击

c# - 除了 System.Type 之外没有任何更多信息的 Cast 对象

c# - 盒装原始值的动态比较

c# - 反射说接口(interface)方法在实现类型中是虚拟的,而实际上它们不是?

c# - 如何从 C# ExpandoObject 按名称动态获取属性?