为什么格式不起作用?

时间:2016-07-07 00:33:27

标签: c# .net format iformatprovider

我有类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();
    }
}

1 个答案:

答案 0 :(得分: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方法中处理默认格式。