我使用的是一个封闭源代码的第三方库,如下所示:
object val = SomeClass.ExtractValue( someObject );
现在,在前面的某个地方,第三方库尝试解析具有意外格式的DateTime值,并抛出FormatException。
在这种情况下,我想检索它没有成功解析的字符串,并尝试自己解析它。如下所示:
object val;
try
{
val = SomeClass.ExtractValue( someObject );
}
catch( FormatException e )
{
string failed = e.GetParseArgument( );
val = DateTime.Parse( failed + " 2010" );
}
是的,简单地添加年份是非常没有意义的,但是您已经明白了。
有没有办法做到这一点?谢谢。
发布于 2010-12-09 18:52:19
由于someObject
是一个IDataReader,您可以创建一个装饰器并将其传递给ExtractValue
。然后,您可以截取日期字符串,并在将其传递到库之前修改格式。
public class DateFormattingDataReader : IDataReader
{
private readonly IDataReader inner;
public DateFormattingDataReader(IDataReader inner)
{
this.inner = inner;
}
public string GetString(int index)
{
string s = this.inner.GetString(index);
if(index == problematicColumnIndex)
{
//try to parse string and then format it for the library
}
else return s;
}
}
或者,您可以记录从读取器读取的所有值,然后您可以获得失败的数据作为最后读取的项,并尝试自己解析它。
https://stackoverflow.com/questions/4401610
复制相似问题