您的位置:首页 > 其它

Attribute注解

2015-10-08 21:14 295 查看
class Program
{
static void Main(string[] args)
{
//Attribute注解,Attribute是附加到方法、属性、类等上面的特殊的标签,在类Type信息初始化的加载
//无法再运行时修改
Type type = typeof(Person);
object[] attrs =
type.GetMethod("Hello").GetCustomAttributes(typeof(RuPengAttribute), false);
for (int i = 0; i < attrs.Length; i++)
{
RuPengAttribute ra = (RuPengAttribute)attrs[i];
Console.WriteLine(ra.Name);
}

/*
Person p1 = new Person();
p1.F1();*/
// type = typeof(SqlConnection);
var methods = type.GetMethods();
foreach (var method in methods)
{
object[] obAttrs = method.GetCustomAttributes(typeof(ObsoleteAttribute), false);
if (obAttrs.Length > 0)
{
ObsoleteAttribute oa = (ObsoleteAttribute)obAttrs[0];
Console.WriteLine("注意,"+method.Name+"不再推荐使用,因为:"+oa.Message);
}
}
Console.ReadKey();
}
}

[Obsolete("这个类不能用,否则后果自负")]
class Person
{
//在Hello方法的描述信息MethodInfo上粘了一个RuPengAttribute对象
//注解的值必须是常量,不能是动态算出来
//[RuPengAttribute(Name=DateTime.Now.ToString())]
//一般特性的类型都以Attribute结尾,这样用的时候就不用写“Attribute”
//Attribute:注解、注释、特性、属性。。。
[RuPeng(Name = "rupeng")]
public void Hello()
{
}
[Obsolete("这个方法有bug,我不想修复了,调用Hello可以达到同样的效果,而且没有没有bug")]
public void F1()
{

}
}


namespace ConsoleApplication2
{
[AttributeUsage(AttributeTargets.Method)]
class RuPengAttribute:Attribute
{
public RuPengAttribute()
{
}

public RuPengAttribute(string name)
{
this.Name = name;
}

public string Name { get; set; }
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: