我认为您不需要阅读 FieldAttribute 属性的库。
public class MyFileLayout
{
[FieldFixedLength(2)]
public string prefix;
[FieldFixedLength(12)]
public string customerName;
}
Type type = typeof(MyFileLayout);
FieldInfo fieldInfo = type.GetField("prefix");
object[] attributes = fieldInfo.GetCustomAttributes(false);
FieldFixedLengthAttribute attribute = (FieldFixedLengthAttribute)attributes.FirstOrDefault(item => item is FieldFixedLengthAttribute);
if (attribute != null)
{
// read info
}
我为此做了一个方法:
public bool TryGetFieldLength(Type type, string fieldName, out int length)
{
length = 0;
FieldInfo fieldInfo = type.GetField(fieldName);
if (fieldInfo == null)
return false;
object[] attributes = fieldInfo.GetCustomAttributes(false);
FieldFixedLengthAttribute attribute = (FieldFixedLengthAttribute)attributes.FirstOrDefault(item => item is FieldFixedLengthAttribute);
if (attribute == null)
return false;
length = attribute.Length;
return true;
}
用法:
int length;
if (TryGetFieldLength(typeof(MyFileLayout), "prefix", out length))
{
Show(length);
}
PS:字段/属性必须是公共的才能通过反射读取它们的属性。