这篇文章介绍了C#中属性(Attribute)的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、创建属性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor, AllowMultiple = true, Inherited = true)]
//AttributeTargets:属性应用到的目标类型。AllowMultiple:是否允许一个元素应用多个此属性。Inherited:属性能否有派生类继承。
public class CodeStatusAttribute : Attribute
{
private string status;
public CodeStatusAttribute(string status)//构造函数为位置参数
{
this.status = status;
}
public string Tester { set; get; }//属性和公共字段为命名参数
public string Coder { set; get; }
public override string ToString()
{
return status;
}
}
二、应用属性
//1、使用单个属性
[CodeStatus("a版")]
public class Tringe
{ }
//2、使用多个属性
[CodeStatus("b版", Coder = "小李")]
[CodeStatus("b版", Coder = "小王")]
//也可以[CodeStatus("aa",Coder="小李"),CodeStatus("aa",Coder="小王")]
public class Square
{ }
//3、使用位置参数和命名参数
//type表示此属性与什么元素关联,可能有:assembly,field,method,param,property,return,moudule,event,type等。。
[type: CodeStatus("最终版", Coder = "小李", Tester = "老李")]
public class Circle
{
[CodeStatus("最终版", Coder = "小李", Tester = "老李")]
public Circle()
{
}
}
三、反射属性
//1、获取类上的属性。
Type t = typeof(Circle);
Attribute[] attArr = Attribute.GetCustomAttributes(t, typeof(CodeStatusAttribute));
//或
object[] attArr1 = t.GetCustomAttributes(typeof(CodeStatusAttribute), true);
//2、获取成员上属性
Attribute[] attArr3 = t.GetConstructors()[0].GetCustomAttributes().ToArray();//构造函数,获取字段GetField("..")
//3、遍历
foreach (Attribute attr in attArr3)
{
CodeStatusAttribute item = (CodeStatusAttribute)attr;
Console.Write(item.ToString() + item.Coder + item.Tester);
}
四、Net内置属性
[Condeitonal] //条件控制
[Obsolete] //废弃属性
[Serializable]//可序列化属性
[AssemblyDelaySign] //程序集延迟签名
到此这篇关于C#属性(Attribute)的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:C#中属性(Attribute)的用法


基础教程推荐
猜你喜欢
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- 实例详解C#实现http不同方法的请求 2022-12-26
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C# 解析XML和反序列化的示例 2023-04-14
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity shader实现高斯模糊效果 2023-01-16
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#中的Linq to JSON操作详解 2023-06-08
- C#中 Json 序列化去掉null值的方法 2022-11-18