C# 如何从FileHelpers库获取指定的固定长度字段?
我正在使用FileHelpers库编写输出文件。以下是示例代码段:C# 如何从FileHelpers库获取指定的固定长度字段?,c#,filehelpers,C#,Filehelpers,我正在使用FileHelpers库编写输出文件。以下是示例代码段: public class MyFileLayout { [FieldFixedLength(2)] private string prefix; [FieldFixedLength(12)] private string customerName; } 在我的代码流中,我想知道在运行时分配长度的每个字段,例如:customerName是12 有没有办法从FileHelpers库中获取上述
public class MyFileLayout
{
[FieldFixedLength(2)]
private string prefix;
[FieldFixedLength(12)]
private string customerName;
}
在我的代码流中,我想知道在运行时分配长度的每个字段,例如:customerName是12
有没有办法从FileHelpers库中获取上述值?我认为您不需要库读取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:字段/属性必须是公共的,才能通过反射读取属性。要获取属性的值吗?是的,但这是特定于FileHelpers库的,我已经发布了一个关于获取属性值的问题,我专门用FileHelpers标记了这个问题,获取属性值将起作用,除非在FileHelpers中,Length属性标记为internal,因此我无法使用这种方式。请参考我之前的问题[()