我有一个网格UserControl。它使用iformatProvider将文本格式化在单元格中进行显示。每个单元格允许设置自己的IformatProvider。根据Cell的DisplayText的要求,Program调用Cell的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.quals。它是功能还是有更好的方法?
注意:我对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