【问题标题】:why format doesn't work?为什么格式不起作用?
【发布时间】:2016-07-07 00:33:26
【问题描述】:

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

【问题讨论】:

  • 投反对票,因为您的问题不清楚。您似乎没有对 CustomerFormatProvider 类的 Format 方法进行任何调用。那你怎么能说在程序执行过程中函数被忽略了呢??
  • @ViVi,它是一个格式提供程序。不会有任何直接调用它的 Format 方法。 @Pavel 上面提到他在调用Customer.Format() 时遇到了错误。虽然他应该提到调用代码,但你投反对票背后的假设可能是不正确的。

标签: c# .net format iformatprovider


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    相关资源
    最近更新 更多