我有一个网格UserControl。它使用IFormatProvider格式化单元格中的文本以供显示。每个单元格允许设置自己的IFormatProvider。在请求单元格的DisplayText时,程序先调用单元格的IFormatProvider,然后依次调用列的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。它是在运行还是有更好的方法?
发布于 2019-05-09 16:42:05
注意:我为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 = 1https://stackoverflow.com/questions/56053426
复制相似问题