C# 反射与特性结合使用:获取和使用自定义特性
在 C# 中,可以通过反射和特性相结合来获取和使用特性。下面是一个简单的示例,演示如何使用反射和特性:
首先,定义一个自定义特性:
[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute
{
public string Name { get; set; }
public MyAttribute(string name)
{
Name = name;
}
}
然后,定义一个带有该特性的类:
[My('MyClass')]
public class MyClass
{
public void MyMethod()
{
Console.WriteLine('MyMethod called.');
}
}
接下来,使用反射获取该类的特性:
Type type = typeof(MyClass);
MyAttribute myAttribute = type.GetCustomAttribute<MyAttribute>();
if (myAttribute != null)
{
Console.WriteLine($'Name: {myAttribute.Name}');
}
输出结果为:Name: MyClass
这里使用 Type 类的 GetCustomAttribute 方法获取 MyAttribute 特性,如果存在该特性,则返回 MyAttribute 对象。如果不存在,则返回 null。
使用反射和特性结合可以使代码更加灵活和可扩展,可以在运行时动态地获取和使用特性,进而改变程序的行为。
原文地址: https://www.cveoy.top/t/topic/nsNB 著作权归作者所有。请勿转载和采集!