[英]How to compare IFormatProvider?
I have an Grid UserControl. 我有一个网格用户控件。 It used IFormatProvider to format Text in a Cell for display.
它使用IFormatProvider格式化单元格中的文本以进行显示。 Each Cell allows to set own IFormatProvider.
每个单元允许设置自己的IFormatProvider。 On request of cell's DisplayText, program calls Cell's IFormatProvider, then Column's IFormatProvider in order.
根据单元格的DisplayText的请求,程序依次调用Cell的IFormatProvider,然后依次调用Column的IFormatProvider。 I make an array to save all non-identical IFormatProvider so that I just need to save ID to retrieve the format.
我制作了一个数组来保存所有不相同的IFormatProvider,因此我只需要保存ID即可检索格式。
How to compare the IFormatProvider? 如何比较IFormatProvider? If they are different, save into the array.
如果它们不同,则保存到阵列中。
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;
}
In above code, I used IFormatProvider.Equals. 在上面的代码中,我使用了IFormatProvider.Equals。 Is it functioning or has better way?
它起作用还是有更好的方法?
Note: All types that I have for IFormatProvider
are custom and implement .ToString
that return unique values. 注意:我为
IFormatProvider
拥有的所有类型都是自定义的,并且实现返回唯一值的.ToString
。 If this is not the case for you this approach will not work. 如果不是这种情况,则此方法将行不通。
After debug, I used .ToString() to check whether duplicated. 调试后,我使用.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;
}
testing code: 测试代码:
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);
Result is as I expect: 结果符合我的预期:
index_newfmt1 = 0
index_newfmt1_ = 0
index_newfmt2 = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.