C#基础之特性
2024-10-08 00:52:05
/// <summary>
/// 使用特性,可以有效地将元数据或声明性信息与代码(程序集、类型、方法、属性等)相关联。 将特性与程序实体相关联后,可以在运行时使用反射这项技术查询特性
/// </summary>
///
[System.AttributeUsage(System.AttributeTargets.Class|System.AttributeTargets.Struct,AllowMultiple = true)]
public class Author : System.Attribute
{
string name;
public double version; public Author(string name)
{
this.name = name;
version = 1.0;
} public string GetName()
{
return name;
}
} // Class with the Author attribute.
[Author("P. Ackerman")]
public class FirstClass
{
// ...
} // Class without the Author attribute.
public class SecondClass
{
// ...
} // Class with multiple Author attributes.
[Author("P. Ackerman"), Author("R. Koch", version = 2.0)]
public class ThirdClass
{
// ...
} class TestAuthorAttribute
{
public static void Test()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
} private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);
foreach(System.Attribute attr in attrs)
{
if(attr is Author)
{
Author a = (Author)attr;
System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
}
}
}
}
查看官网复习一下相关概念,随手记录一下,以便以后翻阅
最新文章
- 斐波拉契数列(Fibonacci) 的python实现方式
- pthread_create 内存释放
- HMM 自学教程(六)维特比算法
- iOS-上拉刷新,下拉加载-----------详解
- Sqlserver_insert语法
- Jquery-json
- How Tomcat Works(四)
- freemarker得到数组的长度
- java 生成pdf报表
- 【转】windows上自动设置java环境变量的脚本
- JS判断PC和移动端设备
- 玩转webpack(二):webpack的核心对象
- android:inputType常用取值
- 属于自己的MES(二)必备的主数据
- Bumped! 2017 ICPC North American Qualifier Contest (分层建图+dijstra)
- jsonp实现ajax跨域
- 第四百零四节,python网站第三方登录,social-auth-app-django模块,
- java中Memcache的使用
- Mac上配置idea的项目上传到GitHub
- VUE2.0 饿了吗视频学习笔记(六):定位问题、文字显示、模糊背景图片、点击事件