C#高级特性_Attribute
2024-09-12 09:49:40
Attribute:
公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型、字段、方法和属性等。Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。
在.NET中,Attribute被用来处理多种问题,比如序列化、程序的安全特征、防止即时编译器对程序代码进行优化从而代码容易调试等等。
使用Attribute的一般方式:
1)在程序集、类、域、方法等前面用[]表示;
2)可以带参数:位置参数(相当于构造方法带的参数)
命名参数(域名或属性名-值)
1.声明Attribute类:
因为attribute从System.Attribute继承而来,名字要用xxxAttribute格式,不然编译器不能识别。
2.使用Attribute类:
1)在类及成员上面使用方括号;
2)可以省略后最Attribute;
3.通过反射访问属性:
能够知道程序中的信息。
代码示例:
using System;
using System.Reflection; [AttributeUsage(AttributeTargets.Class
| AttributeTargets.Method ,
AllowMultiple = true)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
private string topic;
public string Topic // 属性 Topic 是命名参数
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url) // url 是位置参数
{
this.Url = url;
}
} [HelpAttribute("http://msvc/MyClassInfo", Topic="Test"),
Help("http://my.com/about/class")]
class MyClass
{
[Help("http;//my.com/about/method")]
public void MyMethod(int i)
{
return;
}
} public class MemberInfo_GetCustomAttributes
{
public static void Main()
{
Type myType = typeof(MyClass); //查看Attribute信息
object[] attributes = myType.GetCustomAttributes(false);
for (int i = ; i < attributes.Length; i ++)
{
PrintAttributeInfo(attributes[i]);
} MemberInfo[] myMembers = myType.GetMembers();
for(int i = ; i < myMembers.Length; i++)
{
Console.WriteLine("\nNumber {0}: ", myMembers[i]);
Object[] myAttributes = myMembers[i].GetCustomAttributes(false);
for(int j = ; j < myAttributes.Length; j++)
{
PrintAttributeInfo( myAttributes[j] );
}
}
} static void PrintAttributeInfo( object attr )
{
if( attr is HelpAttribute )
{
HelpAttribute attrh = (HelpAttribute) attr;
Console.WriteLine( "----Url: " + attrh.Url + " Topic: " + attrh.Topic );
Console.ReadKey(true);
}
}
}
最新文章
- PHP严重致命错误处理:php Fatal error: Cannot redeclare class or function
- C语言中关于对目录的操作
- 后缀数组---Milk Patterns
- Bootstrap页面布局24 - BS旋转木马功能
- Java笔记——面向切面编程(AOP模式)
- VC++创建、调用dll的方法步骤
- 9. memcpy() memccpy() memmove() strcpy() memset()
- 关于51单片机P0口的结构及上拉问题
- ThinkPHP - 关联模型 - 多对多
- python_如何对迭代器进行切片操作
- Install Windows 2016 on VirtualBox
- EntityFramework Core 2.1重新梳理系列属性映射(一)
- 跟踪mqttv3源码(一)
- Exploit-Exercises nebule 旅行日志(四)
- python主流测试框架的简介
- [JVM-1]Java运行时数据区域
- 【算法随记】Canny边缘检测算法实现和优化分析。
- How to make an IntelliJ IDEA plugin in less than 30 minutes
- springboot 前后端分离项目跨域配置
- 【Java】Java-ShutDownHook-优雅关闭系统资源