-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();
    }
}
4

1 回答 1

0

我猜问题在于您如何调用该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方法中处理默认格式。

于 2016-07-07T04:50:42.470 回答