Domanda

I have a class which is defined as

public class SerializableList<TList, TValue> : IXmlSerializable where TList : IList<TValue>

The issue comes when trying to implement the constructor to make sure I have a TList object.

public SerializableList()
{
    FList = new TList();
}

Which throws the expected error of not having a new() constraint. As I want to be able to use the definition of

var myList = new SerializableList<SortedList<string>, string>();

does this mean I have looking at things the wrong way, or is there a way I can define the new FList object?

È stato utile?

Soluzione

public class SerializableList<TList, TValue> : IXmlSerializable
    where TList : IList<TValue>, new()

Altri suggerimenti

What you want are Generic Type Constraints

In your instance the class declaration needs to be

public class SerializableList<TList, TValue> 
    : IXmlSerializable where TList : IList<TValue>, new()

Where new() enforces that TList must have a parameterless constructor

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top