我试图弄清楚 IFormatProvider 和 ICustomFormatter在 DataGridView 列中的 Format TimeSpan 如何在 DataGridView 中自定义 TimeSpan 之后如何工作。我创建了一个完全自定义的格式化程序,无论格式化什么,它总是返回“foo”。
我在 Int 上使用它,但我认为它应该适用于所有类型,因为它不检查传递的值,它只是返回"foo"
.
class MyFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
Console.WriteLine("GetFormat");
return this;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
Console.WriteLine("Format");
return "foo";
}
}
我将它传递给int.ToString()
:
int number = 10;
Console.WriteLine(number.ToString(new MyFormatter()));
我得到的是:
获取格式 10
虽然我希望得到的是:
获取格式 格式 富
编辑:我发现如何为 DateTime 创建和使用自定义 IFormatProvider?并且那里的答案说除了或DateTime.ToString()
之外什么都不会接受,如果一个对象不是这些类型,即使它实现了,它也会被拒绝- https://stackoverflow.com/a/2382481/492336。DateTimeFormatInfo
CultureInfo
ICustomFormatter
所以我的问题是,这是否适用于所有ToString()
方法的情况?它是否也适用于 DataGridView,在哪些情况下我可以传递真正自定义的格式化程序?