2011-10-12 90 views
2

我使用MonoTouch的工作,一個iPhone的項目,我需要序列化和保存一個簡單的對象屬於C#類與CLLocation類型的數據成員:MonoTouch:如何序列化未標記爲可序列化的類型(如CLLocation)?

[Serializable] 
public class MyClass 
{ 
    public MyClass (CLLocation gps_location, string location_name) 
    { 
     this.gps_location = gps_location; 
     this.location_name = location_name; 
    } 

    public string location_name; 
    public CLLocation gps_location; 
} 

這是我的二進制序列化方法:

static void SaveAsBinaryFormat (object objGraph, string fileName) 
    { 
     BinaryFormatter binFormat = new BinaryFormatter(); 
     using (Stream fStream = new FileStream (fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { 
      binFormat.Serialize (fStream, objGraph); 
      fStream.Close(); 
     } 
    } 

但是,當我執行此代碼(myObject的是上面的類的實例):

try { 
      SaveAsBinaryFormat (myObject, filePath); 
      Console.WriteLine ("object Saved"); 
     } catch (Exception ex) { 
      Console.WriteLine ("ERROR: " + ex.Message); 
     } 

我得到這個例外? n:

ERROR: Type MonoTouch.CoreLocation.CLLocation is not marked as Serializable.

有沒有辦法用CLLocation序列化一個類?

回答

5

由於類沒有用SerializableAttribute標記,因此無法序列化。但是,通過一些額外的工作,您可以存儲所需的信息並對其進行序列化,同時將其保存在對象中。

您可以通過爲其創建一個屬性並使用適當的後備存儲來完成此操作,具體取決於您想要的信息。例如,如果我只希望CLLocation對象的座標,我將創建以下文件:

[Serializable()] 
public class MyObject 
{ 

    private double longitude; 
    private double latitude; 
    [NonSerialized()] // this is needed for this field, so you won't get the exception 
    private CLLocation pLocation; // this is for not having to create a new instance every time 

    // properties are ok  
    public CLLocation Location 
    { 
     get 
     { 
      if (this.pLocation == null) 
      { 
       this.pLocation = new CLLocation(this.latitude, this.longitude); 
      } 
      return this.pLocation; 

     } set 
     { 
      this.pLocation = null; 
      this.longitude = value.Coordinate.Longitude; 
      this.latitude = value.Coordinate.Latitude; 
     } 

    } 
} 
+0

謝謝,工作就像一個魅力! –

2

不能添加到[Serializable] MonoTouch的類型。另一種選擇(對Dimitris極好的建議)是在你自己的類型上使用ISerializable

這將使您完全控制如何從您的類型序列化數據。您也可以混合使用兩種方法,如果可能的話使用[Serializable],否則在項目中使用ISerializable

相關問題