Attribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReflectionClass
{
public enum Fruit
{
Apple,
Banana,
Pear,
Watermelon
}

public class FruitTypeAttribute:System.Attribute
{
public FruitTypeAttribute(Fruit fruit)
{
this.fruit = fruit;
}

protected Fruit fruit;
public Fruit TheFruit
{
get { return fruit; }
set { fruit = value; }
}
}

public class FruitTest:IFruit
{
[FruitType(Fruit.Apple)]
public void AppleMethod() { }

[FruitType(Fruit.Pear)]
public void PearMethod() { }
}
}

在使用Attribute的时候[FruitType(Fruit.Apple)]实际上就是实现了FruitTypeAttribute的构造方法,而在构造方法中又为TheFruit属性赋值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
class AssemblyTest
{
public static Assembly ReflectionClassAssembly
{
get
{
return Assembly.Load("ReflectionClass");
}
}

public static void ShowAttributeInfo()
{
//object fruitTest = ReflectionClassAssembly.CreateInstance("ReflectionClass.FruitTest");
Type fruitTest = ReflectionClassAssembly.GetType("ReflectionClass.FruitTest");
MethodInfo method
= fruitTest.GetMethod("AppleMethod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);//可省略第二个参数

Type fruitType
= ReflectionClassAssembly.GetType("ReflectionClass.FruitTypeAttribute");
Attribute attr
= Attribute.GetCustomAttribute(method, fruitType);
if (attr!=null)
{
PropertyInfo property
= fruitType.GetProperty("TheFruit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);//可省略第二个参数
Console.WriteLine("the {0} attribute is : {1}", method.Name, property.GetValue(attr, null));
}
//Attribute[] attrs = Attribute.GetCustomAttributes(method);
//if (attrs.Length > 0)
//{
//Console.WriteLine("the {0} attribute is : {1}",method.Name,property.GetValue(attrs[0],null));
//((ReflectionClass.FruitTypeAttribute)attrs[0]).TheFruit
//}
}
}
}

原文地址:https://www.cnblogs.com/xingbinggong/p/2154040.html