创建一个特性ShowAttribute继承Attribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyAttribute.ShowExtend
{
//表示现在可以标记多个特性和子类特性
[AttributeUsage(AttributeTargets.All,AllowMultiple =true,Inherited =true)]
public class ShowAttribute:Attribute
{
public string ShowInfo { get; set; }
public void Show()
{
Console.WriteLine(ShowInfo);
}
}
}
首先创建一个ShowTest测试类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyAttribute.ShowExtend
{
[Show(ShowInfo="我是在类上的特性")]
[Show(ShowInfo = "我是在类上的第二个特性")]
public class ShowTest
{
[Show(ShowInfo = "我是在方法上的特性")]
public void TestMethod()
{
}
[Show(ShowInfo = "我是在属性上的特性")]
public string TestProper { get; set; }
[Show(ShowInfo = "我是在字段上的特性")]
public string TestField;
}
}
创建一个特性调用类,而且具有泛型的扩展方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MyAttribute.ShowExtend
{
//扩展方法实现泛型
public static class InvokeCenter
{
public static void InvokeManager<T>( this T showTest) where T:new()
{
Type type = showTest.GetType();
if (type.IsDefined(typeof(ShowAttribute),true))
{
//在类上查找特性
object[] attributes = type.GetCustomAttributes(typeof(ShowAttribute), true);
foreach (ShowAttribute attribute in attributes)
{
attribute.Show();
}
//在方法上查找特性
foreach (MethodInfo method in type.GetMethods())
{
if (method.IsDefined(typeof(ShowAttribute), true))
{
object[] attributeMethods = type.GetCustomAttributes(typeof(ShowAttribute), true);
foreach (ShowAttribute attribute in attributeMethods)
{
attribute.Show();
}
}
}
//在属性上查找特性
foreach (PropertyInfo property in type.GetProperties())
{
if (property.IsDefined(typeof(ShowAttribute), true))
{
object[] attributeMethods = property.GetCustomAttributes(typeof(ShowAttribute), true);
foreach (ShowAttribute attribute in attributeMethods)
{
attribute.Show();
}
}
}
//在字段上查找特性
foreach(FieldInfo fieldInfo in type.GetFields())
{
if (fieldInfo.IsDefined(typeof(ShowAttribute), true))
{
object[] attributeFields = fieldInfo.GetCustomAttributes(typeof(ShowAttribute), true);
foreach (ShowAttribute attribute in attributeFields)
{
attribute.Show();
}
}
}
}
}
}
}
在Main函数中进行调用
static void Main(string[] args)
{
//实验二,普通方法,要实例化对象作为参数进行传递。特性调用中心也不需要static类static方法
//ShowTest showTest = new ShowTest();
//InvokeCenter invokeCenter = new InvokeCenter();
//invokeCenter.InvokeManager<ShowTest>(showTest);
ShowTest showTest = new ShowTest();
showTest.InvokeManager();
Console.ReadKey();
}