Usefull Attribute of c#

博主完成短信项目,采用cmpp协议的pdu,决定从头构建。在描述pdu时遇到丢失数据类型、长度等信息的问题,利用C#的属性特性,创建CmppFieldAttribute类来保存信息,完善了抽象基类,解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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.

 

转载于:https://www.cnblogs.com/mahope/archive/2004/11/23/67278.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值