对象在尝试返回元组时必须实现IConvertible
本文关键字:实现 IConvertible 元组 返回 对象 | 更新日期: 2023-09-27 18:18:31
在运行时,我得到以下错误
"Object必须实现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">
它在我用//error标记的地方出错
ConvertType
是一种方法,可以让您将实现IConvertable
的对象转换为一组固定的对象(字符串,数字类型等),它不仅不能将任何IConvertible
对象转换为任何类型的Tuple
(如果您查看该接口的方法,您将看到原因),而且您正在调用它的Tuple
不是IConvertible
,因为错误消息告诉您。
当然,解决方案是首先不调用ChangeType
。它的存在是为了将对象从一种类型转换为另一种类型,但是您拥有的对象已经是正确的类型,您只需要通知编译器编译时表达式应该是不同的,并且您知道类型在运行时总是匹配的。您只需使用常规强制转换:
tmp = (Tuple<bool,T,object>) (object) I(o.ToString());
试试这个。这会忽略"Object must implementation 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);
}