-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();
}
}
因为您的问题不清楚,因此需要进行投票。您似乎没有任何对“CustomerFormatProvider”类的Format方法的调用。那么你怎么能说在程序执行过程中该函数被忽略? – ViVi
@ViVi,这是一个formatprovider。不会有任何直接调用它的“格式”方法。 @Pavel上面提到他在调用'Customer.Format()'时面临错误。虽然他应该提及调用代码,但您的downvote背后的假设可能不正确。 – Ash