【问题标题】:MonoTouch : How to serialize a type (like CLLocation) not marked as Serializable?MonoTouch:如何序列化未标记为可序列化的类型(如 CLLocation)?
【发布时间】:2011-12-06 08:11:23
【问题描述】:

我正在使用 MonoTouch 处理一个 iPhone 项目,我需要序列化并保存一个属于具有 CLLocation 类型作为数据成员的 c# 类的简单对象:

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

我得到了这个例外:

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

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

【问题讨论】:

    标签: ios serialization xamarin.ios serializable cllocation


    【解决方案1】:

    由于一个类没有用 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;
            }
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      您不能将[Serializable] 添加到 MonoTouch 类型。另一种选择(Dimitris 的极好建议)是在您自己的类型上使用ISerializable

      这将使您完全控制如何序列化您的类型中的数据。您也可以混合使用这两种方法,在可能的情况下使用[Serializable],否则在项目中使用ISerializable

      【讨论】:

        猜你喜欢
        • 2015-02-15
        • 2016-07-23
        • 1970-01-01
        • 2019-12-15
        • 2011-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-27
        相关资源
        最近更新 更多