如何比较IFormatProvider?

时间:2019-05-09 06:30:09

标签: c# iformatprovider

我有一个Grid UserControl。它使用IFormatProvider格式化单元格中的文本以进行显示。每个单元允许设置自己的IFormatProvider。根据单元格的DisplayText的请求,程序依次调用Cell的IFormatProvider,然后依次调用Column的IFormatProvider。我制作了一个数组来保存所有不相同的IFormatProvider,因此我只需要保存ID即可检索格式。

如何比较IFormatProvider?如果它们不同,则保存到数组中。

private IFormatProvider[] FormatProviders;

internal short CreateNewFormatProviders(IFormatProvider newFormatProvider)
{
    if (newFormatProvider == null) // (IFormatProvider.Equals(newFormatProvider,null))
    {
        return -1;
    }
    int len = this.FormatProviders.Length;
    for (int i = 0; i < len; i++)
    {
        if (IFormatProvider.Equals(this.FormatProviders[i],newFormatProvider))
        {
            return (short)i;
        }
    }
    Array.Resize<IFormatProvider>(ref this.FormatProviders, len + 1);
    this.FormatProviders[len] = newFormatProvider;
    return (short)len;
}        

在上面的代码中,我使用了IFormatProvider.Equals。它起作用还是有更好的方法?

1 个答案:

答案 0 :(得分:0)

注意:我为IFormatProvider拥有的所有类型都是自定义的,并且实现了返回唯一值的.ToString。如果不是这种情况,则此方法将无效。

调试后,我使用.ToString()检查是否重复。

private IFormatProvider[] FormatProviders = new IFormatProvider[1];
internal short CreateNewFormatProviders(IFormatProvider newFormatProvider)
    {             
        if (newFormatProvider == null) // (IFormatProvider.Equals(newFormatProvider,null))
        {
            return -1;
        }

        if (this.FormatProviders[0] == null)
        {
            this.FormatProviders[0] = newFormatProvider;
            return 0;
        }

        int len = this.FormatProviders.Length;
        for (int i = 0; i < len; i++)
        {
            //if (IFormatProvider.Equals(this.FormatProviders[i],newFormatProvider)) *always return False*
            if (newFormatProvider.ToString() == this.FormatProviders[i].ToString()) 
            {
                return (short)i;
            }
        }
        Array.Resize<IFormatProvider>(ref this.FormatProviders, len + 1);
        this.FormatProviders[len] = newFormatProvider;
        return (short)len;
    }

测试代码:

   IFormatProvider newfmt1 = new CustomFormatProvider1();
   IFormatProvider newfmt1_ = new CustomFormatProvider1();
   IFormatProvider newfmt2 = new CustomFormatProvider2();
   short index_newfmt1 = CreateNewFormatProviders(newfmt1);
   short index_newfmt1_= CreateNewFormatProviders(newfmt1_);
   short index_newfmt2= CreateNewFormatProviders(newfmt2);

结果符合我的预期:

      index_newfmt1 = 0
      index_newfmt1_ = 0
      index_newfmt2 = 1