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);
}
}