C# 对象在尝试返回元组时必须实现IConvertible

C# 对象在尝试返回元组时必须实现IConvertible,c#,C#,在运行时,我得到以下错误 “对象必须实现IConvertible” 调用函数 lboxBuildingType.SelectedIndex = pharse.returning<int>xdoc.Root.Element("BuildingTypeIndex").Value); public static T returning<T>(object o) { Tuple<bool, T, object> tmp; switch (

在运行时,我得到以下错误

“对象必须实现IConvertible”

调用函数

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);
}
lboxBuildingType.SelectedIndex=pharse.returningxdoc.Root.Element(“BuildingTypeIndex”).Value);
公共静态T返回(对象o)
{
元组tmp;
开关(Type.GetTypeCode(typeof(T)))
{
////废话废话
case TypeCode.Int32:
tmp=(Tuple)Convert.ChangeType(I(o.ToString())),typeof(T));//错误
打破
////废话废话
}
}
私有静态元组I(对象o)
{
int i;
布尔b;
Int32.TryParse(o.ToString(),out i);
b=(i==0);
返回新的元组(b,i,o);
}
代码的目的是传入一个
(“15”)
,并让它生成一个
元组
,即
元组


它在我用//error标记的地方出错

ConvertType
是一种方法,允许您将实现
IConvertable
的对象转换为一组固定对象(字符串、数字类型等)中的一个,它不仅不能将任何
IConvertable
对象转换为任何类型的
元组
(如果您查看该接口的方法,您将看到原因。)但是您正在调用它的
元组
不是错误消息告诉您的
IConvertible

当然,解决方案是首先不要调用
ChangeType
。它的存在是为了将对象从一种类型转换为另一种类型,但是您拥有的对象已经是正确的类型,您只需要通知编译器编译时表达式应该不同,并且您知道该类型在运行时总是匹配的时间。你只需要一个普通演员就可以做到:

tmp = (Tuple<bool,T,object>) (object) I(o.ToString());
tmp=(元组)(对象)I(o.ToString());
尝试此操作。这会忽略“对象必须实现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);
    } 

您可以使用泛型类型约束:使用列表对象而不是元组。列表对象具有IConvertible的内置方法。@Sven泛型类型约束无法解决此问题。如果您检查泛型类型,则几乎总是出错。@jdweng这只会将错误从一个更改为另一个;即使他有一个
IConvertible
,他试图将其转换为的对象也不是
IConvertible
支持的对象。