【发布时间】:2019-05-09 06:30:08
【问题描述】:
我有一个网格用户控件。它使用 IFormatProvider 格式化单元格中的文本以进行显示。每个 Cell 允许设置自己的 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。它是否有效或有更好的方法?
【问题讨论】:
-
IFormatProvider没有“名称”的概念...所以不完全清楚您打算比较什么(显然您已经确认大多数ToString调用返回相同的类型值有问题,所以我假设帖子中的代码只是你想做的一个例子) -
虽然edit 发帖澄清第一个问题,但我建议完全删除第二个问题(因为您已经搜索过它并找到了stackoverflow.com/questions/605621/… 之类的东西)-否则将考虑发帖“太宽泛”并且已关闭(加上帖子可能会被拒绝,因为您没有显示搜索 bing.com/search?q=c%23+size+of+object+in+memory 的结果)。
-
根据我的测试,IFormatProvider.Equals 不起作用。IFormatProvider newfmt = new CustomFormatProvider(); IFormatProvider newfmt2 = new CustomFormatProvider();Console.WriteLine(object.Equals(newfmt, newfmt2)); Console.WriteLine(IFormatProvider.Equals(newfmt, newfmt2)); Console.WriteLine(newfmt == newfmt2);全部返回False。
-
object.ToString() 返回我的自定义 IFormatProvider 的名称,它可以识别正在使用的接口。
标签: c# iformatprovider