2009-08-05 7 views
0

int를 특정 형식으로 변환 한 다음 변환 한 형식에 따라 형식이 다른 문자열을 반환하려고합니다.
Type 개체를 반환하는 속성 및 형식에 따라 형식이 다른 문자열을 반환 할 속성이 있습니다.
왜 HexString의 코드가 컴파일러와 비슷하지 않습니까?
똑같이 간단한 방법이 있습니까?C# ChangeType 및 ToString?

public class TestClass 
{ 
    private int value; 
    public bool signed; 
    public int nBytes; 

    public int Value { get {return value;} set {this.value = value;}} 

    public Type Type { 
     get { 
      switch (this.nBytes) { 
      case 1: 
       return (this.signed ? typeof(SByte) : typeof(Byte)); 
      case 2: 
       return (this.signed ? typeof(Int16) : typeof(UInt16)); 
      default: 
       return null; 
      } 
     } 
    } 

    public String HexString { 
     get { 
      //?? compiler error: "no overload for method 'ToString' takes '1' arguments 
      return (Convert.ChangeType(this.Value, this.Type)).ToString("X" + this.nBytes); 
     } 
    } 
} 
+0

이것은 대답이 아닙니다. 단지 제안입니다. 제네릭을 사용하면 도움이 될지도 모릅니다. –

답변

3

오히려 Object.ToString()을 사용하는 것보다 String.Format를 통해 문자열을 포맷하십시오 :

return String.Format("{0:x" + this.nBytes.ToString() + "}", 
    (Convert.ChangeType(this.Value, this.Type))); 

Formattable가 ToString() 방법은 System.Object.ToString()를 오버라이드 (override)되지 않고, 같은 당신이 매개 변수와 함께 Object에 해당 메서드를 호출 할 수 없습니다를 구현하는 모든 유형을 .

1

ChangeType은 System.Object를 반환합니다. 불행히도 숫자 형만 ToString 오버로드에 형식 (문자열 매개 변수)을 제공합니다. System.Object.ToString()은 매개 변수를 사용하지 않습니다.