首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何比较IFormatProvider?

如何比较IFormatProvider?
EN

Stack Overflow用户
提问于 2019-05-09 14:30:09
回答 1查看 89关注 0票数 1

我有一个网格UserControl。它使用IFormatProvider格式化单元格中的文本以供显示。每个单元格允许设置自己的IFormatProvider。在请求单元格的DisplayText时,程序先调用单元格的IFormatProvider,然后依次调用列的IFormatProvider。我创建了一个数组来保存所有不相同的IFormatProvider,因此我只需要保存ID来检索格式。

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

代码语言:javascript
复制
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。它是在运行还是有更好的方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-09 16:42:05

注意:我为IFormatProvider提供的所有类型都是自定义的,并且实现了返回唯一值的.ToString。如果情况并非如此,则此方法将不起作用。

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

代码语言:javascript
复制
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;
    }

测试代码:

代码语言:javascript
复制
   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);

结果如我所料:

代码语言:javascript
复制
      index_newfmt1 = 0
      index_newfmt1_ = 0
      index_newfmt2 = 1
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56053426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档