C#自定义特性和反射

本文详细介绍了C#中的自定义特性概念,如何在实体类中应用特性,并通过反射在运行时获取并利用这些特性,提升代码的灵活性和可扩展性。
摘要由CSDN通过智能技术生成
反射需要一整本书来讨论,这里只介绍了Type类和Assembly类,他们是访问反射所提供的拓展功能的主要入口点。这里介绍了自定义特性,它比其它方面更常用,以及如何在运行期间检索自定义特性信息。

一、自定义特性

内置的特性可以根据特性来影响编译。

自定义特性可以在运行期间获取程序信息,可以影响执行程序的方式。例如自定义特性可以用于支持对自定义许可类进行声明性的代码访问   安全检查,把信息与程序元素关联起来,程序元素由测试工具使用,或者在开发可拓展的架构时允许加载插件和模块。 
特性的使用:
编译器发现[FieldName("socialsecurityNumber")]时,会把字符串Attribute追加到这个名称后面,形成一个组合名称FieldNameAttribute   ,然后搜索所在的名称空间(包括using的)搜索有指定名称的类。 
自定义特性,继承自:Attribute

using System;
namespace WhatsNewAttributes
{
    [AttributeUsage( // AttributeUsage是.net定义的特性的内置特性说明,可以叫特性的元特性。
        AttributeTargets.Class | AttributeTargets.Method,// 应用到的程序元素[必选],使用时候如果是assembly或module的可以放
置在代码中的任何地方
        AllowMultiple = true, // 同一个程序元素上是否可以使用多次[可选]
        Inherited = false)] // 是否可以继承,接口/类,如果是属性方法那么重载属性方法中也会影响[可选]
    public class LastModifiedAttribute : Attribute
    {
        private readonly DateTime _dateModified;
        private readonly string _changes;
 // 有两个必选参数
        public LastModifiedAttribute(string dateModified, string changes)
        {
            _dateModified = DateTime.Parse(dateModified);
            _changes = changes;
        }
 
 //没有set函数,是因为需要作为构造函数参数传入,不能内部指定。
        public DateTime DateModified
        {
            get { return _dateModified; }
        }

        public string Changes
        {
            get { return _changes; }
        }
 // 这个属性为可选参数
        public string Issues { get; set; }
    }

    [AttributeUsage(AttributeTargets.Assembly)]
    public class SupportsWhatsNewAttribute : Attribute
    {
    }
}

二、实体类中使用特性

using System;
using System.Collections;
using System.Text;
using WhatsNewAttributes; // 引入特性定义类

// 声明该程序集使用全局的SupportsWhatsNewAttribute特性类
[assembly: SupportsWhatsNew]

namespace VectorClass
{
    // 使用LastModifiedAttribute特性类
    [LastModified("14 Feb 2010", "IEnumerable interface implemented " +
                                 "So Vector can now be treated as a collection")]
    [LastModified("10 Feb 2010", "IFormattable interface implemented " +
           
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值