The object must implement IConvertible when trying to return a tuple

At runtime, I get the following error

"Object must implement IConvertible"

calling function

lboxBuildingType.SelectedIndex = pharse.returning<int>xdoc.Root.Element("BuildingTypeIndex").Value);

public static T returning<T>(object o)
{
       Tuple<bool, T, object> tmp;
       switch (Type.GetTypeCode(typeof(T)))
       {
        ////blah blah blah
           case TypeCode.Int32:
              tmp= (Tuple<bool,T,object>)Convert.ChangeType(I(o.ToString())), typeof(T)); // error
              break;
        ////blah blah blah
       }
}

private static Tuple<bool, Int32, Object> I(object o)
{
      int i;
      bool b;
      Int32.TryParse(o.ToString(), out i);
      b = (i == 0);
      return new Tuple<bool, Int32, object>(b, i, o);
}

The purpose of the code is to convey and create tuple<Bool,T,object>that willtuple<true, 15, "15">

Errors where I marked them with an error //

+4
source share
2 answers

ConvertTypeis a method that allows you to convert objects that implement IConvertable, into one of the fixed sets of objects (strings, numeric types, etc.). It not only cannot convert any object IConvertibleto any type Tuple(If you look at the methods of this interface, you will understand why.), But Tuplewith which you are calling it is not IConvertible, as an error is reported to you.

, , ChangeType . , , , , , , , . :

tmp = (Tuple<bool,T,object>) (object) I(o.ToString());
+3

. "Object IConvertible", GUID:

public object ChangeType(object value, Type type)
    {
        if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
        if (value == null) return null;
        if (type == value.GetType()) return value;
        if (type.IsEnum)
        {
            if (value is string)
                return Enum.Parse(type, value as string);
            else
                return Enum.ToObject(type, value);
        }
        if (!type.IsInterface && type.IsGenericType)
        {
            Type innerType = type.GetGenericArguments()[0];
            object innerValue = ChangeType(value, innerType);
            return Activator.CreateInstance(type, new object[] { innerValue });
        }
        if (value is string && type == typeof(Guid)) return new Guid(value as string);
        if (value is string && type == typeof(Version)) return new Version(value as string);
        if (!(value is IConvertible)) return value;
        return Convert.ChangeType(value, type);
    } 
0

Source: https://habr.com/ru/post/1612261/


All Articles