C# Serializing a Collection of Objects

后端 未结 3 1472
遇见更好的自我
遇见更好的自我 2021-01-07 01:45

I am working on a ASP.NET application that has a class that inherits a List of a Custom Object.

public class UserRoleList : List {
    publ         


        
相关标签:
3条回答
  • 2021-01-07 02:28

    I believe you really just need to ensure that UserRoleBO is serializable and the list will take care of itself. This assumes the values you want to serialize are public properties on the UserRoleBO and UserList. For more info see What is the point of the ISerializable interface?

    0 讨论(0)
  • 2021-01-07 02:42

    You need to do the following

    1. Ensure UserRoleList is serializable
    2. Ensure UserRoleBO is serializable
    3. Ensure the type of all fields inside UserRoleBO are serializable (this is recursive)

    The easiest way to do this is to add the [Serializable] attribute to the classes. This will work in most cases.

    On a different note, deriving from List<T> is usually speaking a bad idea. The class is not meant to be derived from and any attempt to specialize it's behavior can be thwarted in sceanarios where the derived class is used from a List<T> reference. Can you explain why you want to derive in this way? There is likely a more robust solution.

    0 讨论(0)
  • 2021-01-07 02:42

    Like so:

    [Serializable]
    public class UserRoleList : List<UserRoleBO> {
        public UserRoleList() { }
    }
    

    (Note the 'Serializble' tag will need to be on all classes that need to be serialised (so the parent as well.

    And then use BinarySerialization to do it.

    0 讨论(0)
提交回复
热议问题