我正在使用 4.0,并试图通过开发一些用于类型转换的辅助方法来简化我的生活。以下方法运行良好。它将从任何字符串转换为其他数据类型。
System.ComponentModel;
public static T Convert<T>(string s)
{
var typeConverter = TypeDescriptor.GetConverter(typeof(T));
if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
{
return (T)typeConverter.ConvertFrom(s);
}
return default(T);
}
//calling this method...
var dateTime = MyConverter.Convert<DateTime>("13/07/2013"); // Date format "DD/mm/yyyy"
// Working as expected... Taking "13" as Day, "07" as month
现在以下方法也在同一个类 MyConverter 中,但它不适用于 DateTime:
public static bool CanConvertTo<T>(string s)
{
var typeConverter = TypeDescriptor.GetConverter(typeof(T));
if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
{
return typeConverter.IsValid(s);
}
else
return false;
}
这种方法的问题是,它只接受日期格式:“MM/dd/yyyy”
// This will give exception. It is taking "13" as month, "07" as Day
bool canConvert = MyConverter.CanConvertTo<DateTime>("13/07/2013");
编辑 根据 KeyboardP 的建议,我将方法更改为:
public static bool CanConvertTo<T>(string s)
{
TypeConverter typeConverter;
if (typeof(T) == typeof(DateTime))
{
typeConverter = new DateTimeConverter();
}
else
{
typeConverter = TypeDescriptor.GetConverter(typeof(T));
}
if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
{
return typeConverter.IsValid(s);
}
else
return false;
}
并经过测试。测试结果是:
var date = MyConverter.Convert<DateTime>("13/07/2013"); //return perfect date
var canConvert = MyConverter.CanConvertTo<DateTime>("13/07/2013"); // returned false...
所以没有成功DateTimeConverter