我正在使用FileHelpers库来编写输出文件。以下是示例代码段:
public class MyFileLayout
{
[FieldFixedLength(2)]
private string prefix;
[FieldFixedLength(12)]
private string customerName;
}
在我的代码流程中,我想知道每个在运行时分配长度的字段,例如:对于customerName,它是12。
有没有办法从FileHelpers库中获取上述值?
答案 0 :(得分:1)
我认为您不需要库读取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:字段/属性必须是公共的才能通过反射读取它们的属性。