如何使用Convert.ChangeType代替DateTime.ParseExact? [英] How can I use Convert.ChangeType instead of DateTime.ParseExact?

查看:141
本文介绍了如何使用Convert.ChangeType代替DateTime.ParseExact?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个解析器类,该类将字符串解析为具有自定义格式的类型

I'm writing a parser class which parses a string to a type with customized format.

例如,我想使用 Parse&DateTime>( 20161018,typeof(DateTime),UnknownFormatProvider)并返回解析的 DateTime ;

For example I want to use Parse<DateTime>("20161018",typeof(DateTime),UnknownFormatProvider) and It returns the parsed DateTime;

我知道我可以使用 DateTime.ParseExact 用于将特定格式的字符串转换为 DateTime ,但是由于上述原因,我必须使用 Convert.ChangeType(object,Type,IFormatProvider)

I know I can use DateTime.ParseExact for converting string with specific format to DateTime but for the mentioned reason I must use Convert.ChangeType(object,Type,IFormatProvider).

是否可以创建 IFormatProvider 用于 Convert.ChangeType(object,Type,IFormatProvider)使其像 DateTime.ParseExact

Is there any way to create an IFormatProvider to use in Convert.ChangeType(object,Type,IFormatProvider) to do make it work just like DateTime.ParseExact?


编辑:也许 System.Globalization.DateTimeFormatInfo 应该起作用,但我
仍然不知道如何将其设置为像 DateTime.ParseExact


解决方案


有什么方法可以创建 IFormatProvider 以在
<$ c中使用$ c> Convert.ChangeType(object,Type,IFormatProvider)使其像 DateTime.ParseExact 一样工作

Is there any way to create an IFormatProvider to use in Convert.ChangeType(object,Type,IFormatProvider) to do make it work just like DateTime.ParseExact?

我不这样认为。

Convert.ChangeType(Object,TypeCode,IFormatProvider) Convert.ChangeType( Object,Type,IFormatProvider)重载使用 IConvertible.ToDateTime(IFormatProvider) 方法用于<< c $ c> TypeCode.DateTime 和 typeof (DateTime)作为第二个参数。

Both Convert.ChangeType(Object, TypeCode, IFormatProvider) and Convert.ChangeType(Object, Type, IFormatProvider) overloads uses IConvertible.ToDateTime(IFormatProvider) method under the hood for TypeCode.DateTime and typeof(DateTime) as a second parameters.

http://referencesource.microsoft.com/#mscorlib/system/convert.cs,206
http://referencesource.microsoft.com/#mscorlib/system/convert.cs,325

此方法解释为;


将此实例的值转换为等效的 DateTime使用
指定的区域性重要的格式信息。

Converts the value of this instance to an equivalent DateTime using the specified culture-specific formatting information.

我认为这两个重载 only 均接受<$使用的标准日期和时间格式c $ c> IFormatProvider 参数,如果那些 object 作为第一个参数是 string

I think both those overloads only accepts standard date and time formats used by IFormatProvider parameter if those object as a first parameter is a string.

这意味着此方法重载不接受第一个参数的任何自定义日期和时间字符串。

This means this method overloads do not accept any custom date and time strings for a first parameter.

这篇关于如何使用Convert.ChangeType代替DateTime.ParseExact?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆