2016-07-07 6 views
-2

고객 클래스가 있고 고객 클래스를 변경하지 않고 다른 형식을 만들어야합니다. 이를 위해 CustomerFormatProvider를 만들었습니다. 그러나 Customer.Format()이 호출되면 CustomFormatProvider.Format은 무시됩니다. 왜 ??? 도와주세요 !!!!형식이 작동하지 않는 이유는 무엇입니까?

public class Customer 
{ 
    private string name; 
    private decimal revenue; 
    private string contactPhone; 

    public string Name { get; set; } 
    public decimal Revenue { get; set; } 
    public string ContactPhone { get; set; } 

    public string Format(string format) 
    { 
     CustomerFormatProvider formatProvider = new CustomerFormatProvider(); 
     return string.Format(formatProvider, format, this); 
    } 
} 
public class CustomerFormatProvider : ICustomFormatter, IFormatProvider 
{ 
    public object GetFormat(Type formatType) 
    { 
     if (formatType == typeof(ICustomFormatter)) 
      return this; 
     return null; 
    } 

    public string Format(string format, object arg, IFormatProvider formatProvider) 
    { 
     Customer customer = (Customer) arg; 
     StringBuilder str = new StringBuilder(); 

     str.Append("Customer record:"); 

     if (format.Contains("N")) 
     { 
      str.Append(" " + customer.Name); 
     } 

     if (format.Contains("R")) 
     { 
      str.Append($"{customer.Revenue:C}"); 
     } 

     if (format.Contains("C")) 
     { 
      str.Append(" " + customer.ContactPhone); 
     } 

     return str.ToString(); 
    } 
} 
+0

질문이 확실하지 않으므로 아래로 투표하십시오. 'CustomerFormatProvider' 클래스의 Format 메서드에 대한 호출이없는 것 같습니다. 그렇다면 프로그램 실행 중에 함수가 무시되고 있다고 어떻게 말할 수 있습니까 ?? – ViVi

+0

@ViVi, 포맷 제공자입니다. 'Format' 메소드는 직접 호출하지 않습니다. @Pavel은'Customer.Format()'을 호출하는 동안 오류가 발생했다는 것을 언급합니다. 그는 호출 코드를 언급해야하지만, downvote 뒤에있는 가정은 잘못된 것입니다. – Ash

답변

0

나는이 문제를 추측에는 요 당신이 Format 메소드를 호출하는 방법입니다. 다음 중 하나를 작동합니다 : 당신은 아마뿐만 아니라 Format 메서드 내에서 서식 기본을 처리해야

var cust = new Customer() {Name="name", Revenue=12M, ContactPhone = "042681494"}; 
var existing = cust.Format("{0:N} - {0:R} - {0:C}"); 
var newImpl = string.Format(new CustomerFormatProvider(), "{0:N} - {0:R} - {0:C}", cust); 

또는

var existing1 = cust.Format("{0:NRC}"); 
var newImpl1 = string.Format(new CustomerFormatProvider(), "{0:NRC}", cust); 

.