2013-08-13 1 views
2

출력 파일을 쓰려면 FileHelpers 라이브러리를 사용하고 있습니다. 내 코드 흐름에서FileHelpers 라이브러리에서 필드의 지정된 고정 길이를 얻으려면 어떻게해야합니까?

public class MyFileLayout 
{ 
    [FieldFixedLength(2)] 
    private string prefix; 

    [FieldFixedLength(12)] 
    private string customerName; 
} 

, 내가 예를 들어, 런타임에 길이 할당 된 각 필드를 알고 싶다 : 다음은 샘플 코드이다가 CUSTOMERNAME 12입니다.

FileHelpers 라이브러리에서 위와 같은 값을 얻을 수있는 방법이 있습니까?

+0

속성 값을 가져 오시겠습니까? – Matten

+0

예,하지만 이것은 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

답변

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); 
     } 

추신 : 필드/속성을 반사와 자신의 특성을 읽기 위해 공개해야합니다.

+0

나는 이것을 특별히 다음과 같이 태그를 붙였다. FileHelpers, FileHelpers를 제외하고 속성 값을 가져 오는 것은 Length 속성이 내부 용으로 decaled되므로이 방법을 사용할 수 없습니다. 내 이전 질문을 참조하십시오 [http://stackoverflow.com/questions/18201971/how-do-i-get-the-custom-attribute-value-of-a-field/] (http://stackoverflow.com/ 질문/18201971/사용자 정의 속성 값 - of-field /를 얻는 방법) – vijay

관련 문제