Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么格式不起作用?_C#_.net_Format_Iformatprovider - Fatal编程技术网

C# 为什么格式不起作用?

C# 为什么格式不起作用?,c#,.net,format,iformatprovider,C#,.net,Format,Iformatprovider,我有客户类,我需要在不改变客户类的情况下制作不同的格式。我为此创建了CustomerFormatProvider。但是当Customer.Format调用时,它会忽略CustomFormatProvider.Format。为什么? 请帮忙 public class Customer { private string name; private decimal revenue; private string contactPhone; public string

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

我猜问题在于如何调用格式化方法。以下任一项均有效:

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方法中处理默认格式。

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