Faster version of Convert.ChangeType

前端 未结 5 1392
北荒
北荒 2021-01-02 04:12

In an application that I have, I am doing quite frequent calls to Convert.ChangeType in order to convert a value to a dynamically loaded type.

However

5条回答
  •  滥情空心
    2021-01-02 04:30

    This is my version of a faster ChangeType. I guess the principle is the same as suggested by @CraigTP, however, it will only work for nullable value types.

    I'm basing my convert method on the fact that it's more likely that the type of value will be compatible with the target type is some way. But this method wasn't designed for performance it was designed to be convenient. It's not something I'd wanna invoke from within a tight loop.

    I'm still falling back on ChangeType but I try to opt out as early as possible.

    public static T? ToOrDefault(object value)
        where T : struct, IConvertible
    {
        var x = value as T?;
        if (x.HasValue)
        {
            return x;
        }
        if (value == null || Convert.IsDBNull(value))
        {
            return null;
        }
        try
        {
            return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
        }
        catch (InvalidCastException)
        {
        }
        catch (FormatException)
        {
        }
        catch (OverflowException)
        {
        }
        catch (ArgumentException)
        {
        }
        return default(T?);
    }
    

提交回复
热议问题