小马

现在是零将来是无限

导航

Usefull Attribute of c#

 

Usefull Attribute of c#
Recently, I have finished a project of sms.
The protocol of pdu is cmpp.

There are a lot of handy source codes available for me. But I decided to build it from scratch.
In the protocol of cmpp, a pdu is made up of a header and a body, the fields of a header are defined as follow:

Field name

Data type

Length

Description

TotalLen

UnsignedInteger

4

The totol length of a pdu.

CmdID

UnsignedInteger

4

The command type identifier

SeqNum

UnsignedInteger

4

The sequence number of a pdu.

The body fields depend on the value of CmdID in the header. But the form of the fields are just like those in the header.

To describe a pdu, it’s nature that I made a base class like this:

// CmppMessage.cs

public abstract class CmppMessage

{

         public int TotalLen;

         public int CmdID;

         public int SeqNum;

}

Then the problem comes: I lost the information such as, Data Type, Length, etc.

When I know there is an attribute thing in c#, I was very excited. I knew the problem may be resolved perfectly.

An attribute named CmppFieldAttribute was created to keep the information of the field of CmppMessage.

// CmppFieldAttribute.cs

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]

public class CmppFieldAttribute:System.Attribute

{

         CmppFieldType m_Type;

int m_Len;

 

public CmppFieldAttribute(CmppFieldType type,int len)

{

         m_Type = type;

         m_Len = len;

}

 

public CmppFieldType FieldType

{

         get{return m_Type;}

         set{m_Type = value;}

}

 

public int Length

{

         get{         return m_Len;}

         set{         m_Len = value;}

}

}

Hence, my abstract base class becomes:

public abstract class CmppMessage

{

    [CmppField(CmppFieldType.UnsignedInteger, 4)]

    public int TotalLen;

    [CmppField(CmppFieldType.UnsignedInteger, 4)]

    public int CmdID;

    [CmppField(CmppFieldType.UnsignedInteger, 4)]

    public int SeqNum;

}

In my final source code there are a lot more property in CmppFieldAttribute class. But the above already show my idea completely.

 

posted on 2004-11-23 01:06  mahope  阅读(785)  评论(0编辑  收藏  举报