Attribute在.net编程中的应用


Attribute在.net编程中的应用(一)

经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行。实际上在.Net中,Attribute是一个非常重要的组成部分,为了帮助大家理解和掌握Attribute,以及它的使用方法,特地收集了几个Attribute使用的例子,提供给大家参考。

在具体的演示之前,我想先大致介绍一下Attribute。我们知道在类的成员中有property成员,二者在中文中都做属性解释,那么它们到底是不是同一个东西呢?从代码上看,明显不同,首先就是它们的在代码中的位置不同,其次就是写法不同(Attribute必须写在一对方括符中)。

数据库中以便查询;或者把信息写到代码的注释里面,这样可以阅读代码的同时看到代码被检查的信息。我们知道.NET的组件是自描述的,那么是否可以让代码自己来描述它被检查的信息呢?这样我们既可以将信息和代码保存在一起,又可以通过代码的自我描述得到信息。答案就是使用Attribute.
下面的步骤和代码告诉你怎么做:
首先,我们创建一个自定义的Attribute,并且事先设定我们的Attribute将施加在class的元素上面以获取一个类代码的检查信息。

using System;
using System.Reflection;
 
[AttributeUsage(AttributeTargets.Class)] //还记得上一节的内容吗?
public class CodeReviewAttribute : System.Attribute //定义一个CodeReview的Attribute
{
 private string reviewer;  //代码检查人
 private string date;      //检查日期
 private string comment;   //检查结果信息

 //参数构造器
 public CodeReviewAttribute(string reviewer, string date)
 {
  this.reviewer=reviewer;
  this.date=date;
 }

 public string Reviewer
 {
  get
  {
   return reviewer;
  }
 }

 public string Date
 {
  get
  {
   return date;
  }
 }

 public string Comment
 {
  get
  {
   return comment;
  }
  set
  {
   comment=value;
  }
 }
}

我们的自定义CodeReviewAttribute同普通的类没有区别,它从Attribute派生,同时通过AttributeUsage表示我们的Attribute仅可以施加到类元素上。

第二步就是使用我们的CodeReviewAttribute, 假如我们有一个Jack写的类MyClass,检查人Niwalker,检查日期2003年7月9日,于是我们施加Attribute如下:

[CodeReview("Niwalker","2003-7-9",Comment="Jack的代码")]
public class MyClass
{
 //类的成员定义
} 

当这段代码被编译的时候,编译器会调用CodeReviewAttribute的构造器并且把"Niwalker"和"2003-7-9"分别作为构造器的参数。注意到参数表中还有一个Comment属性的赋值,这是Attribute特有的方式,这里你可以设置更多的Attribute的公共属性(如果有的话),需要指出的是.NET Framework1.0允许向private的属性赋值,但在.NET Framework1.1已经不允许这样做,只能向public的属性赋值。

第三步就是取出我们需要的信息,这是通过.NET的反射来实现的,关于反射的知识,限于篇幅我不打算在这里进行说明,也许我会在以后另外写一篇介绍反射的文章。

class test
{
   static void Main(string[] args)
   {
      System.Reflection.MemberInfo info=typeof(MyClass); //通过反射得到MyClass类的信息
      //得到施加在MyClass类上的定制Attribute 
      CodeReviewAttribute att = (CodeReviewAttribute)Attribute.GetCustomAttribute(info,typeof(CodeReviewAttribute)); 
      if(att!=null)
      {
          Console.WriteLine("代码检查人:{0}",att.Reviewer);
          Console.WriteLine("检查时间:{0}",att.Date);
          Console.WriteLine("注释:{0}",att.Comment);
      }
   }
}

在上面这个例子中,Attribute扮演着向一个类添加额外信息的角色,它并不影响MyClass类的行为。通过这个例子,我们大致可以知道如何写一个自定义的Attribute,以及如何在应用程序使用它。下一节,我将介绍如何使用Attribute来自动生成ADO.NET的数据访问类的代码。

Attribute在.net编程中的应用(三)

SqlCommandGenerator类的设计

SqlCommandGEnerator类的设计思路就是通过反射得到方法的参数,使用被SqlCommandParameterAttribute标记的参数来装配一个Command实例。

引用的命名空间:

//SqlCommandGenerator.cs

using System;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using Debug = System.Diagnostics.Debug;
using StackTrace = System.Diagnostics.StackTrace;  

类代码:

namespace DataAccess
{
   public sealed class SqlCommandGenerator
   {
      //私有构造器,不允许使用无参数的构造器构造一个实例
      private SqlCommandGenerator()
      {
         throw new NotSupportedException();
      }

      //静态只读字段,定义用于返回值的参数名称
      public static readonly string ReturnValueParameterName = "RETURN_VALUE";
      //静态只读字段,用于不带参数的存储过程
      public static readonly object[] NoValues = new object[] {};
   
      
      public static SqlCommand GenerateCommand(SqlConnection connection,
                                  MethodInfo method, object[] values)
      {
         //如果没有指定方法名称,从堆栈帧得到方法名称
         if (method == null)
             method = (MethodInfo) (new StackTrace().GetFrame(1).GetMethod());

         // 获取方法传进来的SqlCommandMethodAttribute
         // 为了使用该方法来生成一个Command对象,要求有这个Attribute。
         SqlCommandMethodAttribute commandAttribute = 
            (SqlCommandMethodAttribute) Attribute.GetCustomAttribute(method, typeof(SqlCommandMethodAttribute));

         Debug.Assert(commandAttribute != null);
         Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure ||
       commandAttribute.CommandType == CommandType.Text);

         // 创建一个SqlCommand对象,同时通过指定的attribute对它进行配置。
         SqlCommand command = new SqlCommand();
         command.Connection = connection;
         command.CommandType = commandAttribute.CommandType;
      
         // 获取command的文本,如果没有指定,那么使用方法的名称作为存储过程名称 
         if (commandAttribute.CommandText.Length == 0)
         {
            Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure);
            command.CommandText = method.Name;
         }
         else
         {
            command.CommandText = commandAttribute.CommandText;
         }

         // 调用GeneratorCommandParameters方法,生成command参数,同时添加一个返回值参数
         GenerateCommandParameters(command, method, values);
         command.Parameters.Add(ReturnValueParameterName, SqlDbType.Int).Direction 
                              =ParameterDirection.ReturnValue;

         return command;
      }

      private static void GenerateCommandParameters(
                           SqlCommand command, MethodInfo method, object[] values)
      {

         // 得到所有的参数,通过循环一一进行处理。
         
         ParameterInfo[] methodParameters = method.GetParameters();
         int paramIndex = 0;

         foreach (ParameterInfo paramInfo in methodParameters)
         {
            // 忽略掉参数被标记为[NonCommandParameter ]的参数
         
            if (Attribute.IsDefined(paramInfo, typeof(NonCommandParameterAttribute)))
               continue;
            
            // 获取参数的SqlParameter attribute,如果没有指定,那么就创建一个并使用它的缺省设置。
            SqlParameterAttribute paramAttribute = (SqlParameterAttribute) Attribute.GetCustomAttribute(
     paramInfo, typeof(SqlParameterAttribute));
   
      if (paramAttribute == null)
         paramAttribute = new SqlParameterAttribute();
      
      //使用attribute的设置来配置一个参数对象。使用那些已经定义的参数值。如果没有定义,那么就从方法 
      // 的参数来推断它的参数值。
      SqlParameter sqlParameter = new SqlParameter();
      if (paramAttribute.IsNameDefined)
         sqlParameter.ParameterName = paramAttribute.Name;
      else
         sqlParameter.ParameterName = paramInfo.Name;

            if (!sqlParameter.ParameterName.StartsWith("@"))
               sqlParameter.ParameterName = "@" + sqlParameter.ParameterName;
         
            if (paramAttribute.IsTypeDefined)
               sqlParameter.SqlDbType = paramAttribute.SqlDbType;
            
            if (paramAttribute.IsSizeDefined)
               sqlParameter.Size = paramAttribute.Size;

            if (paramAttribute.IsScaleDefined)
               sqlParameter.Scale = paramAttribute.Scale;
            
            if (paramAttribute.IsPrecisionDefined)
               sqlParameter.Precision = paramAttribute.Precision;
            
            if (paramAttribute.IsDirectionDefined)
            {
               sqlParameter.Direction = paramAttribute.Direction;
            }
            else
            {
               if (paramInfo.ParameterType.IsByRef)
               {
                  sqlParameter.Direction = paramInfo.IsOut ? 
                              ParameterDirection.Output : 
                              ParameterDirection.InputOutput;
               }
               else
               {
                  sqlParameter.Direction = ParameterDirection.Input;
               }
            }
         
            // 检测是否提供的足够的参数对象值
     Debug.Assert(paramIndex < values.Length);
           
           //把相应的对象值赋于参数。
           sqlParameter.Value = values[paramIndex];
           command.Parameters.Add(sqlParameter);
                  
                  
           paramIndex++;
         }
      
         //检测是否有多余的参数对象值
         Debug.Assert(paramIndex == values.Length);
      }
   }
}

必要的工作终于完成了。SqlCommandGenerator中的代码都加上了注释,所以并不难读懂。下面我们进入最后的一步,那就是使用新的方法来实现上一节我们一开始显示个那个AddCustomer的方法。

重构新的AddCustomer代码:

[ SqlCommandMethod(CommandType.StoredProcedure) ]
public void AddCustomer( [NonCommandParameter] SqlConnection connection, 
                   [SqlParameter(50)] string customerName, 
                   [SqlParameter(20)] string country, 
                   [SqlParameter(20)] string province, 
                   [SqlParameter(20)] string city, 
                   [SqlParameter(60)] string address, 
                   [SqlParameter(16)] string telephone,
                   out int customerId )
{
   customerId=0; //需要初始化输出参数
  //调用Command生成器生成SqlCommand实例
   SqlCommand command = SqlCommandGenerator.GenerateCommand( connection, null, new object[]
{customerName,country,province,city,address,telephone,customerId } );
                         
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();

   //必须明确返回输出参数的值
   customerId=(int)command.Parameters["@CustomerId"].Value;
}

代码中必须注意的就是out参数,需要事先进行初始化,并在Command执行操作以后,把参数值传回给它。受益于Attribute,使我们摆脱了那种编写大量枯燥代码编程生涯。 我们甚至还可以使用Sql存储过程来编写生成整个方法的代码,如果那样做的话,可就大大节省了你的时间了,上一节和这一节中所示的代码,你可以把它们单独编译成一个组件,这样就可以在你的项目中不断的重用它们了。

Attribute在.net编程中的应用(五)

(承上节) .NET Framework拦截机制的设计中,在客户端和对象之间,存在着多种消息接收器,这些消息接收器组成一个链表,客户端的调用对象的过程以及调用返回实行拦截,你可以定制自己的消息接收器,把它们插入了到链表中,来完成你对一个调用的前处理和后处理。那么调用拦截是如何构架或者说如何实现的呢?

在.NET中有两种调用,一种是跨应用域(App Domain),一种是跨上下文环境(Context),两种调用均通过中间的代理(proxy),代理被分为两个部分:透明代理和实际代理。透明代理暴露同对象一样的公共入口点,当客户调用透明代理的时候,透明代理把堆栈中的帧转换为消息(上一节提到的实现IMessage接口的对象),消息中包含了方法名称和参数等属性集,然后把消息传递给实际代理,接下去分两种情况:在跨应用域的情况下,实际代理使用一个格式化器对消息进行序列化,然后放入远程通道中;在跨上下文环境的情况下,实际代理不必知道格式化器、通道和Context拦截器,它只需要在向前传递消息之前对调用实行拦截,然后它把消息传递给一个消息接收器(实现IMessageSink的对象),每一个接收器都知道自己的下一个接收器,当它们对消息进行处理之后(前处理),都将消息传递给下一个接收器,一直到链表的最后一个接收器,最后一个接收器被称为堆栈创建器,它把消息还原为堆栈帧,然后调用对象,当调用方法结果返回的时候,堆栈创建器把结果转换为消息,传回给调用它的消息接收器,于是消息沿着原来的链表往回传,每个链表上的消息接收器在回传消息之前都对消息进行后处理。一直到链表的第一个接收器,第一个接收器把消息传回给实际代理,实际代理把消息传递给透明代理,后者把消息放回到客户端的堆栈中。从上面的描述我们看到穿越Context的消息不需要格式化,CLR使用一个内部的通道,叫做CrossContextChannel,这个对象也是一种消息接收器。

有几种消息接收器的类型,一个调用拦截可以在服务器端进行也可以在客户端进行,服务器端接收器拦截所有对服务器上下文环境中对象的调用,同时作一些前处理和后处理。客户端的接收器拦截所有外出客户端上下文环境的调用,同时也做一些前处理和后处理。服务器负责服务器端接收器的安装,拦截对服务器端上下文环境访问的接收器称为服务器上下文环境接收器,那些拦截调用实际对象的接收器是对象接收器。通过客户安装的客户端接收器称为客户端上下文环境接受器,通过对象安装的客户端接收器则称为特使(Envoy)接收器,特使接收器仅拦截那些和它相关的对象。客户端的最后一个接收器和服务器端的第一个接收器是CrossContextChannel类型的实例。不同类型的接收器组成不同的段,每个段的端点都装上称为终结器的接收器,终结器起着把本段的消息传给下一个段的作用。在服务器上下文环境段的最后一个终结器是ServerContextTerminatorSink。如果你在终结器调用NextSink,它将返回一个null,它们的行为就像是死端头,但是在它们内部保存有下一个接收器对象的私有字段。

我们大致介绍了.NET Framework的对象调用拦截的实现机制,目的是让大家对这种机制有一个认识,现在是实现我们代码的时候了,通过代码的实现,你可以看到消息如何被处理的过程。首先是为我们的程序定义一个接收器CallTraceSink:

 

//TraceContext.cs

using System;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Activation;

namespace NiwalkerDemo
{
   public class CallTraceSink : IMessageSink //实现IMessageSink
   {
      private IMessageSink nextSink;  //保存下一个接收器
      
      //在构造器中初始化下一个接收器
      public CallTraceSink(IMessageSink next)
      {
         nextSink=next;
      }
      
      //必须实现的IMessageSink接口属性
      public IMessageSink NextSink
      {
         get
         {
            return nextSink;
         }
      }
      
      //实现IMessageSink的接口方法,当消息传递的时候,该方法被调用
      public IMessage SyncProcessMessage(IMessage msg)
      {
         //拦截消息,做前处理
         Preprocess(msg);
         //传递消息给下一个接收器
         IMessage retMsg=nextSink.SyncProcessMessage(msg);
         //调用返回时进行拦截,并进行后处理
         Postprocess(msg,retMsg);
         return retMsg;
      }
      
      //IMessageSink接口方法,用于异步处理,我们不实现异步处理,所以简单返回null,
      //不管是同步还是异步,这个方法都需要定义
      public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
      {
         return null;
      }
      
      //我们的前处理方法,用于检查库存,出于简化的目的,我们把检查库存和发送邮件都写在一起了,
      //在实际的实现中,可能也需要把Inventory对象绑定到一个上下文环境,
      //另外,可以将发送邮件设计为另外一个接收器,然后通过NextSink进行安装
      private void Preprocess(IMessage msg)
      {
         //检查是否是方法调用,我们只拦截Order的Submit方法。
         IMethodCallMessage call=msg as IMethodCallMessage;
         
         if(call==null)
            return;
         
         if(call.MethodName=="Submit")
         {
            string product=call.GetArg(0).ToString(); //获取Submit方法的第一个参数
            int qty=(int)call.GetArg(1); //获取Submit方法的第二个参数
            
            //调用Inventory检查库存存量
            if(new Inventory().Checkout(product,qty))
               Console.WriteLine("Order availible");
            else
            {
               Console.WriteLine("Order unvailible");
               SendEmail();
            }
          }
       }
       
       //后处理方法,用于记录订单提交信息,同样可以将记录作为一个接收器
       //我们在这里处理,仅仅是为了演示
       private void Postprocess(IMessage msg,IMessage retMsg)
       {
          IMethodCallMessage call=msg as IMethodCallMessage;
          
          if(call==null)
             return;
          Console.WriteLine("Log order information");
       }
       
       private void SendEmail()
       {
          Console.WriteLine("Send email to manager");
       }
    }  
        ...  

接下来我们定义上下文环境的属性,上下文环境属性必须根据你要创建的接收器类型来实现相应的接口,比如:如果创建的是服务器上下文环境接收器,那么必须实现IContributeServerContextSink接口。 

      ...
public class CallTraceProperty : IContextProperty, IContributeObjectSink
{
   public CallTraceProperty()
   {
   }
   
   //IContributeObjectSink的接口方法,实例化消息接收器
   public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink next)
   {
      return new CallTraceSink(next);
   }
   
   //IContextProperty接口方法,如果该方法返回ture,在新的上下文环境中激活对象
   public bool IsNewContextOK(Context newCtx)
   {
      return true;
   }
   
   //IContextProperty接口方法,提供高级使用
   public void Freeze(Context newCtx)
   {
   }
   
   //IContextProperty接口属性
   public string Name
   {
      get { return "OrderTrace";}
   }
}
         ...

最后是ContextAttribute

  ...
   [AttributeUsage(AttributeTargets.Class)]
   public class CallTraceAttribute : ContextAttribute
   {
      public CallTraceAttribute():base("CallTrace")
      {
      }
      
      //重载ContextAttribute方法,创建一个上下文环境属性
      public override void GetPropertiesForNewContext(IConstructionCallMessage ctorMsg)
      {
         ctorMsg.ContextProperties.Add(new CallTraceProperty());
      }
   }
}


为了看清楚调用Order对象的Submit方法如何被拦截,我们稍微修改一下Order类,同时把它设计为ContextBoundObject的派生类: 

//Inventory.cs

//Order.cs
using System;

namespace NiwalkerDemo
{
   [CallTrace]
   public class Order : ContextBoundObject
   {
      ...
      public void Submit(string product, int quantity)
      {
         this.product=product;
         this.quantity=quantity;
      }
    ...
   }
}


客户端调用代码: 

...
public class AppMain
{
   static void Main()
   {
      Order order1=new Order(100);
      order1.Submit("Item1",150);
      
      Order order2=new Order(101);
      order2.Submit("Item2",150);
   }
}
...

运行结果表明了我们对Order的Sbumit成功地进行了拦截。需要说明的是,这里的代码仅仅是作为对ContextAttribute应用的演示,它是粗线条的。在具体的实践中,大家可以设计的更精妙。

后记:本来想对Attribute进行更多的介绍,发现要讲的东西实在是太多了。请允许我在其他的专题中再来讨论它们。十分感谢大家有耐心读完这个系列。如果这里介绍的内容在你的编程生涯有所启迪的话,那么就是我的莫大荣幸了。再一次谢谢大家。

原文地址:Attribute在.net编程中的应用

出处:https://www.cnblogs.com/go-jzg/p/6747191.html

C