クラス Customer があり、Customer クラスを変更せずにさまざまな形式を作成する必要があります。このために 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();
}
}