2011-11-04 2 views
0

원하는 경우 사용자가 클라이언트 복사본을 인쇄 할 수 있도록 허용하려고합니다. 나는 다음과 같은 형식으로, 전체 클래스 객체가 서식있는 텍스트 상자 컨트롤에 설정 한 문자열로 변환 가진 떨어져 생각했다 :ToString 메서드에서 클래스 변수 사이에 공백 삽입 C#

Name: blah blah 

Age: blah blah 

Email: blah blah 

Description: blah blah blah 
blah blah blah blah blah 

등 등 줄 간격을 달성하는 간단한 방법이 있나요/특수 서식? 사전에

감사합니다, 예를 들어, 사용 format strings 아리

+0

모두 감사합니다. – Ari

답변

6

:

string.Format("{0}: {1}{2}", "Name", this.Name, Environment.NewLine); 

사용 Environment.NewLine 올바른 개행 문자/S를 얻을.

+0

고맙습니다. :) – Ari

1

당신은 사용자 정의 서식을 제공하기 위해 String.Format()를 사용할 수 있습니다

class YourClass 
{ 
    public override string ToString() 
    { 
     return String.Format(CultureInfo.CurrentCulture, 
          "Description: {0} {1}{2}{3}", 
          this.Name, 
          this.Age, 
          Environment.NewLine, 
          this.Email); 
    } 
} 

이 출력됩니다 :

Description: Name 
Age Email 
1

나는 당신이 사람이라는 클래스를 사용하면 모든 소품을 얻기 위해, ToString 메소드를 오버라이드 (override) 할 수있는 가정 값을 반영하여 인쇄하면 새 속성을 추가해도 코드가 변경되지 않습니다.

 public override string ToString() 
     { 
      var props = GetType().GetProperties(); 

      string result = ""; 
      foreach (var prop in props) 
      { 
       var val = prop.GetValue(this, null); 
       var strVal = val != null ? val.ToString() : string.Empty; 
       result += prop.Name + " : " + strVal + Environment.NewLine; 
      } 
      return result; 
     } 

    } 

또한 직렬화 할 수 있으며 클라이언트 측에서 단지 디 ASCII화할 수 있습니다. 클래스를 직렬화 가능으로 표시하면 쉽습니다.

1
public override string ToString() 
    { 
     return string.Join(Environment.NewLine, 
      GetType().GetProperties().Select( 
      item => item.Name + ": " + (item.GetValue(this, null) ?? string.Empty).ToString() 
      )); 
    }