Attribute.GetCustomAttribute 方法 在.net文档中我们可以看到有许多的重载
例如:
//应用
[Defind]
public class Class1
{
}
//创建
public class DefindAttribute : Attribute
{
public DefindAttribute()
{
Console.WriteLine("特性创建");
}
}
//调用
public class textinvoke
{
public void text() {
Type type1 = typeof(Class1);
Assembly assembly1 = type1.Assembly;
// DefindAttribute attribute1 = Attribute.GetCustomAttribute(assembly1, typeof(DefindAttribute)) as DefindAttribute;
DefindAttribute attribute1 = Attribute.GetCustomAttribute(type1, typeof(DefindAttribute)) as DefindAttribute;
Console.WriteLine(attribute1);
}
}
在我们实现textinvoke类中的text方法时会发现attribute1返回是null,这是因为我们并没有把特性应用到程序集中 ,当我们把GetCustomAttribute中第一个参数换为type时此时能成功调用是因为我们重载了GetCustomAttribute(MemberInfo, Type)这个方法所以我们使用时只需要根据指定需求查找文档调用即可。
除了用Attribute类中的GetCustomAttribute方法获取指定特性以外我们还可以用System.Reflection 中CustomAttributeExtensions类中的GetCustomAttribute扩展方法
扩展方法是什么
文档上扩展方法的解释是 使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种静态方法,但可以像扩展类型上的实例方法一样进行调用。
例如:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this string str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
-----------------
string s = "Hello Extension Methods";
int i = s.WordCount();
//扩展方法也能正常调用
string s = "Hello Extension Methods";
int i = MyExtensions.WordCount(s);
现在我们再看CustomAttributeExtensions类中的GetCustomAttribute方法
例如public static Attribute? GetCustomAttribute (this System.Reflection.MemberInfo element, Type attributeType);
可以看出这是对Memberinfo的扩展 所以Memberinfo类下所有的子类都能用这个扩展方法
例如:
[Defind1]
public class Class1
{
[Defind1]
public void cs(int a)
{
Console.WriteLine("反射调用");
}
}
//创建
public class Defind1Attribute : Attribute
{
public Defind1Attribute()
{
Console.WriteLine("特性创建");
}
}
//调用
//类上
Type type2 = typeof(Class1);
var customAttribute1 = type2.GetCustomAttribute(typeof(Defind1Attribute));
//方法上
MethodInfo method = type2.GetMethod("cs");
var customAttribute2 = method.GetCustomAttribute(typeof(Defind1Attribute));
可以根据自己需要选择对应重载