特性的运用

1
给一个方法添加过时的信息的时候 可以
[Obsolete("方法以及过时,请使用更好的算法EatNice()")]
public string Eat()
{
return "吧唧吧唧的吃";
}
编译一下就可以,下次调用就会显示了

2
右击生成自动会生成一个特性类继承Attribute
[Vip]
public int Age { get; set; }

3 [Vip(true)]------》其实就是调用VipAttribute的构造函数所以这样写的话在VipAttribute中就必须有个带参数的构造函数
[Vip(false)]---特性就new了一个VipAttribute是一个方法实咧
//[Vip5]
public class Pig

4
/// <summary>
/// 特性标签的特点:
/// 1、它是一个类,并且继承了Attribute
/// 2、最好以Attribute结尾,但是不是强制要求的
/// 3、[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]:表示当前标签只能贴在类和方法上,如果贴在其他成员上则会报错
/// 4、 AllowMultiple = true:表示标签可以贴多个
/// 5、 Inherited = true:贴了VipAttribute标签的类可以被它的子类继承
/// </summary>

5 //1.0 获取Pig类的Type类型
Type type = typeof(Pig);
//2.0 获取Pig上面的Vip特性标签
//var attss=type.GetCustomAttributes(false); //获取pig类上的所有特性标签,以数组的形式返回
object[] arrAtts= type.GetCustomAttributes(typeof(VipAttribute), false);
foreach (var item in arrAtts)
{
VipAttribute instane = item as VipAttribute;//内部其实已经new VipAttribute 所以它里面的方法可以点出来------
instane.check();
}


//3.0 判断Pig类上是否贴有Vip5的特性标签
bool isOk = type.IsDefined(typeof(Vip5Attribute), false);


6


//根据不同的对象类的名称 生成对应的表单操作
//1.0 通过反射获取指定类中的所有属性
Type type = typeof(Cat);
PropertyInfo[] pros = type.GetProperties();
foreach (PropertyInfo item in pros)
{
//1.0.1 获取当前item属性上的特性标签DisplayNAttribute
//DisplayNAttribute instance = item.GetCustomAttribute(typeof(DisplayNAttribute)) as DisplayNAttribute; 别人的没报错
DisplayNAttribute instance = item.GetCustomAttributes(typeof(DisplayNAttribute),false)[0] as DisplayNAttribute;//老提示没这个方法所以换了方法
//1.0.2 获取当前DisplayNAttribute中的DispalyName属性的值
string dispName = instance.DisplayName;

tb.AppendFormat("<tr><th>{0}</th><td><input type ="text" id="{1}" name="{1}" /></td></tr>", dispName, item.Name);
}

tb.Append("</table>");

原文地址:https://www.cnblogs.com/cdaq/p/4417287.html