[C#]Convert.ChangeType Invalid cast from ‘System.String’ to ‘System.Guid’解决方法

好像是第三次在写代码的时候遇到这个坑了,在利用反射调用Convert.ChangeType进行类型推算自动转换的时候,总是无法完成string到guid的转换,并且报错

An exception of type 'System.InvalidCastException' occurred in mscorlib.dll but was not handled in user code
Additional information: Invalid cast from 'System.String' to 'System.Guid'.

解决方法便是对Guid的类型对一个单独的处理,通过Guid.Parse,对于其他类型,继续使用Convert.ChangeType

  
public static object ConvertToType(string value, Type targetType)
{
    try
    {
        Type underlyingType = Nullable.GetUnderlyingType(targetType);

        if (underlyingType != null)
        {
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
        }
        else
        {
            underlyingType = targetType;
        }
        switch (underlyingType.Name)
        {
            case "Guid":
                return Guid.Parse(value);
            default:
                return Convert.ChangeType(value, underlyingType);
        }
    }
    catch
    {
        return null;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *