How can I add generic list to a serializable class? |
mark4asp posted on Friday, June 01, 2007 8:17 AM
|
I write this code (below) and I get a compilation error:
System.Collections.Generic.List<int>' is a 'type' but is used like a
'variable'
on this line: Incumbents = info.GetValue("Incumbents",
List<int>);
yet when I look at SerializationInfo I see this header:
public object GetValue(string name, Type type);
[Serializable()]
private class ActivityData : ISerializable
{
public int ActivityID = 0;
public List<int> Incumbents = null;
public DateTime ClosingDate = new DateTime(1753, 1, 1);
public ActivityData()
{
}
protected ActivityData(SerializationInfo info, StreamingContext
context)
{
ActivityID = info.GetInt32("ActivityID");
Incumbents = info.GetValue("Incumbents", List<int>);
ClosingDate = info.GetDateTime("ClosingDate");
}
void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context)
{
info.FullTypeName = "Administration_MandateEdit+ActivityData";
info.AddValue("ActivityID", ActivityID);
info.AddValue("Incumbents", Incumbents);
info.AddValue("ClosingDate", ClosingDate);
}
} |
 |
|
How can I add generic list to a serializable class? |
Jon Skeet [C# MVP] posted on Friday, June 01, 2007 8:31 AM
|
Looks like you need typeof(List<int>).
I do not know whether that will work at runtime or not, but it will
compile...
Jon |
 |
|
Hi,Unless you class needs to make some custom serialization I would stick with |
Ignacio Machin \( .NET/ C# MVP \) posted on Friday, June 01, 2007 9:59 AM
|
Hi,
Unless you class needs to make some custom serialization I would stick with
the provided mechanism.
List<int> is serializable so unless you have another members in your class
just decorate your class with [Serializable()]
The framework will take care of the case where the member is null for you. |
 |
|
How can I add generic list to a serializable class? |
ktrvnbq0 posted on Friday, June 01, 2007 10:21 AM
|
Additionally you would need to typecast the return value from the
GetValue(...) call.
i.e. Incumbents = (List<int>) info.GetValue("Incumbents",
typeof(List<int>)); |
 |
|