Test if Convert.ChangeType will work between two types

后端 未结 4 1159
悲哀的现实
悲哀的现实 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:05

    I was just encountering this same issue, and I used Reflector to look at the source for ChangeType. ChangeType throws exceptions in 3 cases:

    1. conversionType is null
    2. value is null
    3. value does not implement IConvertible

    After those 3 are checked, it is guaranteed that it can be converted. So you can save a lot of performance and remove the try{}/catch{} block by simply checking those 3 things yourself:

    public static bool CanChangeType(object value, Type conversionType)
    {
        if (conversionType == null)
        {
            return false;
        }
    
        if (value == null)
        {              
            return false;
        }
    
        IConvertible convertible = value as IConvertible;
    
        if (convertible == null)
        {
            return false;
        }
    
        return true;
    }
    

提交回复
热议问题