为什么格式不起作用

本文关键字:不起作用 格式 为什么 | 更新日期: 2023-09-27 17:55:41

我有类客户,我需要在不更改客户类的情况下制作不同的格式。我为此创建了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();
    }
}

为什么格式不起作用

我猜问题在于您如何调用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);

您可能还应该在 Format 方法中处理默认格式。