特性类似于代码注释,但特性能从程序中通过反射获取,注释是获取不到的
里面创建2个属性
public class People
{
public int Id { get; set; }
public string name { get; set; }
}
然后建立一个特性类CustomerAttribute.cs
/// <summary>
/// 特性就是一个类,继承Attribute即可
/// 通常以Attribute结尾
/// </summary>
public class CustomerAttribute:Attribute
{
private string Name = "";
private int Vision = 1;
public CustomerAttribute(string name, int vision)
{
this.Name = name;
this.Vision = vision;
}
public void show()
{
Console.WriteLine("作者是{0},系统版本号为{1}",this.Name,this.Vision);
}
}
再将People.cs类前面加上特性
[Customer("Eleven",2)]//特性Customer
public class People
{
public int Id { get; set; }
public string name { get; set; }
}
这样我们在控制台应用程序里面运用反射就可获取到People类上面的特性
Type type = typeof(People);
object[] attrubuteArray = type.GetCustomAttributes(typeof(CustomerAttribute), true);
if (attrubuteArray != null && attrubuteArray.Length>0)
{
((CustomerAttribute)attrubuteArray[0]).show();
}
最终显示: ,就获取到People的特性值了
同样的也可以通过反射获取枚举的特性
public static class RemarkExtention
{
public static string GetRemark(this Enum enumValue)
{
//通过反射 获取对象
//找到RemarkAttribute
//绕后调用GetDescrition对象
//返回提示
FieldInfo type = enumValue.GetType().GetField(enumValue.ToString());
object[] attrubuteArray = type.GetCustomAttributes(typeof(RemarkAttribute), true);
if (attrubuteArray != null && attrubuteArray.Length > 0)
{
return ((RemarkAttribute)attrubuteArray[0]).GetDescription();
}
else
{
return enumValue.ToString();
}
}
}
public class RemarkAttribute : Attribute
{
private string Description = "";
public RemarkAttribute(string description)
{
this.Description = description;
}
public string GetDescription()
{
return this.Description;
}
}
public enum UserState
{
/// <summary>
/// 正常状态
/// </summary>
[Remark("正常状态")]
Normal = 0,
/// <summary>
/// 冻结状态
/// </summary>
[Remark("冻结状态")]
Frozen = 1,
/// <summary>
/// 删除状态
/// </summary>
[Remark("删除状态")]
Deleted = 2
}
控制台中调用: Console.WriteLine(UserState.Deleted.GetRemark()); 输出的为删除状态
源码链接:https://pan.baidu.com/s/1MpoLMGdbYOEPVSdZHMcA_g 密码:utqf