开发者

How best to serialize a list of entities in C#

开发者 https://www.devze.com 2023-03-30 23:20 出处:网络
I have the following method to serialize a list of classes to disk: private static void Serialize(List<CcmAlarmUalUsl> entityList)

I have the following method to serialize a list of classes to disk:

private static void Serialize(List<CcmAlarmUalUsl> entityList)
{
    try
    {
        using (Stream stream = File.Open("CcmAlarmUalUsl.dat", FileMode.Create))
        {
            BinaryFormatt开发者_运维知识库er bin = new BinaryFormatter();
            bin.Serialize(stream, entityList);
        }
    }
    catch (IOException)
    {
    }
}

The entity class I want to serialize looks like this:

public class CcmAlarmUalUsl
{
    public string SubId { get; set; }

    public System.DateTime TimeOfAlarm { get; set; }

    public int AlarmType { get; set; }
}

Is my Serialize class the best way to serialize the list of entities to disk? This does not need to be human readable. It is to be used strictly by the application, as a storage means for an internal cache. No database storage is necessary.

I'm also a bit concerned about when it comes time to modify the structure of CcmAlarmUalUsl. I could be adding properties to the end of the class. How will this affect existing cached items?


The best way, depends on your application requirements. The binary serialization (standart one) is usually cheap in terms of memory used on hard disk, but not very scalable, as one time you refactore your code, you will face deserialization problem of previously saved binaries. Which is possible to resolve but I personally don't like that approach and try to avoid it as much as possible.

Consider:

  1. XML serialization
  2. Json serialization
  3. Save object to SQLite DB with some lightweight ORM.
  4. Custom binary serialization...

There plenty other types out there, but these ones IMHO are more defused ones in these days.

Hope this helps.


Simple answer - no. Your code won't compile (lizards1??) and your CcmAlarmUalUs1 class isn't marked as serializable (run-time error). Mark your CcmAlarmUrlUs1 class as serializable, change lizards1 to entityList and it should work and it looks like you're doing things fine.

You're question is kind of vague, though. By 'best', what are you looking for? Without knowing that, it's hard to really give a good answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消