C# 使用特性进行成员变量反射 - 详细教程
C# 使用特性对成员变量进行反射,可以帮助开发者在运行时获取成员变量的额外信息。以下是实现步骤和代码示例:
- 声明自定义特性类:
[AttributeUsage(AttributeTargets.Field)]
public class MyAttribute : Attribute
{
public MyAttribute(string name)
{
Name = name;
}
public string Name { get; set; }
}
- 在成员变量上添加特性:
public class MyClass
{
[MyAttribute('age')]
public int Age;
[MyAttribute('name')]
public string Name;
}
- 使用反射获取特性信息:
var myClass = new MyClass();
var fields = myClass.GetType().GetFields();
foreach (var field in fields)
{
var attributes = field.GetCustomAttributes(typeof(MyAttribute), true);
foreach (var attribute in attributes)
{
var myAttribute = (MyAttribute)attribute;
Console.WriteLine($'Field name: {field.Name}, Attribute name: {myAttribute.Name}');
}
}
输出结果为:
Field name: Age, Attribute name: age
Field name: Name, Attribute name: name
以上代码使用了反射获取了MyClass类中的所有成员变量,并获取了每个成员变量上的MyAttribute特性的属性值。
原文地址: https://www.cveoy.top/t/topic/nuCf 著作权归作者所有。请勿转载和采集!