在用c#写程序的时候,可能会用到自定义属性来传递一些数据,这次就来简单看看自定义属性的用法:
1.写自定义属性类
a.声明自定义属性类,继承自Attribute类
b.定义所需的构造函数,字段和属性
c.添加AttributeUsageAttribute属性
[AttributeUsage(AttributeTargets.Field)]
public sealed class ByteCountAttribute:Attribute
{
private Int32 length;
public ByteCountAttribute(Int32 len)
{
length = leh;
}
public Int32 Length
{
get{ return length;}
set{ length = value;}
}
}
2.给类中字段或属性增加自定义属性(因为自定义属性的AttributeUsage的构造参数为AttributeTargets.Field)
public class TransData
{
[ByteCount(5)]
public int[] veriData;//需要5个元素,20个字节
[ByteCount(5)]
public double[] horiData;//需要5个元素,40个字节
public TransData()
{
veriData = new int[5];
horiData = new double[5];
}
}
3.通过type获得类字段或属性的自定义属性的值
a.字段用type.GetFields()属性用type.GetProperties()来获取
b.然后用GetCustomAttribute来获取自定义属性
public class Utils
{
public static int GetByteCount(object obj)
{
int byteCount = 0;
Type type = obj.GetType();
foreach(var field in type.GetFields())
{
Type t = field.FieldType;
if(t.IsArray)
{
TypeCode typeCode = Type.TypeCode(t);
switch(typeCode)
{
case Type.Int32:
byteCout += 4 * GetArraySize(field);
break;
case Type.Double:
byteCout += 8 * GetArraySize(field);
break;
default:
break;
}
}
}
return byteCount;
}
private static int GetArraySize(FieldInfo fieldInfo)
{
var bcAttri = (ByteCountAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(ByteCountAttribute));
return bcAttri.Length;
}
}