문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top