Description:
Mysql.Data.Types.MysqlDateTime类型
是实现了IConvertible接口
但几个实现都是有问题的
TypeCode GetTypeCode(); 返回 TypeCode.Empty
String ToString(IFormatProvider provider); 返回null
Object ToType(Type conversionType, IFormatProvider provider); 无论conversionType传入什么类型,均返回null
这是完全不符合预期的
How to repeat:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var mtime = new MySql.Data.Types.MySqlDateTime(DateTime.Now);
var time = DateTime.Now;
Console.WriteLine(Convert(mtime)); //null
Console.WriteLine(Convert(time));
Console.WriteLine(GetString(mtime)); //null
Console.WriteLine(GetString(time));
Console.WriteLine(System.Convert.ToString(mtime)); //null
Console.WriteLine(System.Convert.ToString(time));
}
static string GetString(object obj)
{
if (obj is IFormattable)
{
return ((IFormattable)obj).ToString(null, null);
}
if (obj is IConvertible)
{
return ((IConvertible)obj).ToString(null);
}
return obj.ToString();
}
static object Convert(IConvertible obj)
{
switch (obj.GetTypeCode())
{
case TypeCode.Empty:
return null;
case TypeCode.Object:
return obj.ToType(typeof(object), null);
case TypeCode.DBNull:
return DBNull.Value;
case TypeCode.Boolean:
return obj.ToBoolean(null);
case TypeCode.Char:
return obj.ToChar(null);
case TypeCode.SByte:
return obj.ToSByte(null);
case TypeCode.Byte:
return obj.ToByte(null);
case TypeCode.Int16:
return obj.ToInt16(null);
case TypeCode.UInt16:
return obj.ToUInt16(null);
case TypeCode.Int32:
return obj.ToInt32(null);
case TypeCode.UInt32:
return obj.ToUInt32(null);
case TypeCode.Int64:
return obj.ToInt64(null);
case TypeCode.UInt64:
return obj.ToUInt64(null);
case TypeCode.Single:
return obj.ToSingle(null);
case TypeCode.Double:
return obj.ToBoolean(null);
case TypeCode.Decimal:
return obj.ToDecimal(null);
case TypeCode.DateTime:
return obj.ToDateTime(null);
case TypeCode.String:
return obj.ToString(null);
default:
throw new InvalidCastException();
}
}
}
}
Suggested fix:
TypeCode GetTypeCode()
returns TypeCode.DateTime;
String ToString(IFormatProvider provider);
returns ((DateTime)value).ToString(provider);
Object ToType(Type conversionType, IFormatProvider provider);
if (conversionType == typeof(DateTime)) return (DateTime)value;
if (conversionType == typeof(string)) return ((DateTime)value).ToString(provider)
if (conversionType == typeof(object)) return this;
if (conversionType == typeof(MySqlDateTime)) return this;
throw new InvalidCastException();