Test if Convert.ChangeType will work between two types

后端 未结 4 1170
悲哀的现实
悲哀的现实 2020-12-03 13:44

This is a follow-up to this question about converting values with reflection. Converting an object of a certain type to another type can be done like this:

o         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 14:13

    Checking the method Convert.ChangeType in reflector I found this in the static constructor:

    ConvertTypes = new Type[] { 
            typeof(Empty), typeof(object), typeof(DBNull), typeof(bool), typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal), 
            typeof(DateTime), typeof(object), typeof(string)
         };
    

    In the end, this method is just checking either if the source is implementing IConvertible or if the target is one of the ConvertTypes above. So your method should look something like this (very rough):

    return (ConvertTypes.Contains(toType) || typeof(IConvertible).IsAssignableFrom(fromType));
    

提交回复
热议问题