简体   繁体   中英

How do I serialize a system type so I can store in viewstate?

I have a property that is a List<BaseValidator> . I need to save this property in viewstate so it exists on postback. I get an error back to indicate that the list isn't serializable.

I've Googled ... and Googled but not got an answer that works yet.

I've also created my own custom class but I still get the error because BaseValidator isn't a simple type.

Anyone got any ideas?

A list is serializable if the generic type is serializable. You should make the generic object and sub objects in your list serializable. Add the [Serializable] tag to these objects.

You can serialize arrays. So edit your class to contain an array property for your list. Set editor browsable to never so it doenst show up in Visual Studio and make your list nonserialized.

using System;
using System.ComponentModel;

[Serializable]
public class MyClass
{
    //property for usage in code. dont serialize
    [NonSerialized]
    public List<BaseValidator> MyList { get; set; }

    // Property for serialization only
    [EditorBrowsable(EditorBrowsableState.Never)]
    public BaseValidator[] MyArray
    {
        get
        {
            return MyList.ToArray();
        }
        set
        {
            MyList = new List<BaseValidator>(value);
        }
    }
}

如果列表不可序列化,则可以始终将类标记为[Serializable]并允许将其存储在ViewState

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM