我正在尝试列出具有特定属性的所有字段,但仍然不太明白 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/