1
我有一个非常简单的函数,我写了大约一百万年前的尝试将字符串转换为另一种类型的函数。对于值类型,数字,枚举,日期时间等非常适用,因此我在解析xml文件值,Web请求结果时总是使用它 - 无论如何。替代“TypeDescriptor”类(因为它未在Windows Phone 7上实现)?
但是,由于“TypeDescriptor”对象未实现(请参阅下面的PC代码示例),所以我的代码无法在Windows Phone 7上运行。任何关于如何实现一个非常简单的字符串的建议 - >在手机上输入转换器类型?
这里是我现有的代码(非手机写的):
internal T ChangeType<T>(object o)
{
Type typeOfT = typeof(T);
// null
if (o == null)
{
return default(T);
}
// are types the same
if (typeOfT == o.GetType())
{
return (T)o;
}
// these are different type - try to see
// if there's a built in convertor
// NOTE: "TypeDescriptor" not implemented on Windows Phone 7
TypeConverter convertor = TypeDescriptor.GetConverter(typeOfT);
if (convertor.CanConvertFrom(o.GetType()))
{
return (T)convertor.ConvertFrom(o);
}
else
{
throw new Exception("Can not convert value to type: " + typeOfT.Name);
}
}