1

TypeDescriptor.GetConverter(Type)a very convientent way序列化/反序列化大量的內置數據類型/從字符串:TypeDescriptor置換PCL

object original = ...; 

string serialized = TypeDescriptor.GetConverter(t).ConvertToInvariantString(original); 
object deserialized = TypeDescriptor.GetConverter(t).ConvertFromInvariantString(serialized); 

不幸的是,TypeDescriptor不是便攜式類庫提供。

是否有規範替代或我們必須回到巨大的開關語句?

+0

@ S.Akbari:謝謝,我已經看到了。我想暫時保持這個問題,以防其他人*找到合適的解決方法。 – Heinzi

+0

根據帖子的查看次數,我懷疑即使有人找到這篇文章併發布它,解決方法。但我相信你的問題是一個很好的問題,它應該得到更多的觀衆和投票,也可能適合未來的訪問者。我建議你給它一個賞金,這樣你就可以提請注意你的問題。 –

回答

1

您不能在PCL項目中使用TypeDescriptor,因爲它不是作爲PCL構建的,它不是跨平臺的。 TypeDescriptor在PCL項目中不可用,並且未列出here

以下組件是一個可移植類庫項目中可用:

mscorlib.dll

System.dll

System.Core.dll

System.Xml.dll

System.ComponentModel.Composition.dll

System.Net.dll

System.Runtime.Serialization.dll

System.ServiceModel.dll

System.Xml.Serialization.dll

System.Windows.dll (from Silverlight)

+0

要求'替換' – Cologler

+0

@科學家實際上沒有替代品和替代'TypeDescriptor'。序列化依賴於TypeDescriptor的框架目前是不可移植的。 –

+0

我建議您鏈接到更新版本的可移植類庫開發頁面,如[this](https://msdn.microsoft.com/en-us/library/gg597391.aspx)。 VS 2010的頁面嚴重過時。 –

2

TypeDescriptor在PCL中不可用,但它可能在實際客戶端上使用 PCL。

這是我用來從Xamarin的Android項目注入單TypeDescriptor變通方法:

PCL:

public interface IPclWorkaround 
{ 
    ConvertFromInvariantString(Type type, string s); 
} 

Xamarin的Android:在PCL

[assembly: Dependency(typeof(PclWorkaround))] 

class PclWorkaround : IPclWorkaround 
{ 
    public object ConvertFromInvariantString(Type type, string s) 
    { 
     return TypeDescriptor.GetConverter(type).ConvertFromInvariantString(s); 
    } 
} 

用法:

var myObject = DependencyService.Get<IPclWorkaround>.ConvertFromInvariantString(type, myString); 
+0

偉大的解決方法,我沒有嘗試過,如果你能指出你在什麼PCL配置文件,以及你成功實現這個'IPclWorkaround'接口並使它使用本地系統工具工作的平臺會很好。 – Shimmy

2

FWIW,在.NET Standard 2.0中幸運的是this is covered
.Net Standard 1.4已經可以使用XF(Xamarin Forms)訪問。希望真正很快(vNext),隨着2.0的正式發佈,Mono以及XF.iOS,XF.Droid,XF.Mac和UWP也將加入該派對,所有這些缺少的API將在XF中提供,如見於this表。