How can I define a shared collection as a constraint in a shared method

Aloha

I have a method with a (pseudo) signature:

public static T Parse<T>(string datadictionary) where T : List<U>

It is not built. How can I limit the method to accept only general List <> objects (which should have a cursor that does not contain T, but something else :)

I need to restrict type T because I need to call a method on it in this code. The type that is passed is a custom collection (list-based).

public class MyCollection<T> : List<T> where T: MyClass, new()
{
    public void Foo();
}


public static T Parse<T>(string datadictionary) where T : MyCollection<U>
{
    T.Foo();
}

-Edoode

+3
source share
3 answers

Well, you can have two types of parameters:

public static T Parse<T, U>(string datadictionary) where T : List<U>

This way you can also find out what U is (at compile time) ...

EDIT: Alternatively (and better) just specify the type of the element and change the type of the return value:

public static List<T> Parse<T>(string datadictionary)

eg.

List<int> data = Parse<int>(whatever);

, List<T> IList<T> .

+8

, , T T : List<U> ( T U)...

List<T> ... List<T> . Collection<T> . , , IList<T>, : new(), :

public static TList Parse<TList, TItem>(string datadictionary)
    where TList : IList<TItem>, new() {...}
+3

You can also do this without specifying a type constraint List<u>

 public static List<T> Parse<T>(string datadictionary) ...
+2
source

All Articles