도서관에 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);
}
추신 : 필드/속성을 반사와 자신의 특성을 읽기 위해 공개해야합니다.
속성 값을 가져 오시겠습니까? – Matten
예,하지만 이것은 FileHelpers 라이브러리에만 해당되며 속성 값을 가져 오는 것과 관련하여 질문을 게시했습니다. [http://stackoverflow.com/questions/18201971/how-do-i-get-the-custom-attribute-value -of-a-field /] (http://stackoverflow.com/questions/18201971/how-do-i-get-the-custom-attribute-value-of-a-field/) – vijay