MonoTouch:如何序列化未标记为Serializable的类型(如CLLocation)?

Ema*_*tta 2 serialization serializable xamarin.ios cllocation ios

我正在使用MonoTouch工作到一个iPhone项目,我需要序列化并保存一个属于ac#class的简单对象,其中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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的二进制序列化方法:

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 ();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是当我执行这段代码时(myObject是上面类的一个实例):

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

我得到这个例外:

错误:类型MonoTouch.CoreLocation.CLLocation未标记为可序列化.

有没有办法用CLLocation序列化一个类?

Dim*_*kos 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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)