2015-10-19 111 views
4

在运行时必须实现IConvertible我收到以下错误对象试图返回一个元组

“对象必须实现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); 
} 

的目的代码是通过<T>("15")并让它产生tuple<Bool,T,object>这将是tuple<true, 15, "15">

它的错误了,我已经有//错误

+0

你可以使用泛型类型约束:http://stackoverflow.com/questions/1096568/how-can-i-use-interface-as -ac-sharp-generic-type-constraint – Sven

+0

使用List <>对象而不是Tuple <>。 List <>对象具有IConvertible的内置方法。 – jdweng

+0

@Sven通用类型约束不能解决这个问题。 – Servy

回答

3

ConvertType标志着它是一个可以让你转换实现IConvertable对象为一组固定的对象之一(字符串,数字类型等)不是方法只是它无法将任何IConvertible对象转换为任何类型的Tuple(如果您查看该接口的方法,您将看到原因),但您调用它的Tuple不是IConvertible作为错误消息告诉你。

当然,解决办法是首先不要致电ChangeType。它存在将对象从一种类型转换为另一种类型,但是您拥有的对象已经是适当类型,您只需通知编译器编译时表达式应该不同,并且您知道该类型将始终在运行时匹配。你只用普通演员就可以做到这一点:

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

试试这个。这忽略“对象必须实现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); 
    }