C # Generics: Passing a List <string> to a method that list <T> expects

I had my first raid on generics, and I understood a little of them. I have a method that should take two lists of any object, match them in different ways, and return matching / unsurpassed objects (the material inside the method is probably not the key here). The goal is to accept any object, be it customers or something else. However, I got confused by getting it to take a "string", I suppose because it is not initialized with the new () keyword and does not look like a normal class.

So, I have a method declaration as follows:

public static compareResult<T> stepCompare<T>(List<T> leftList, List<T> rightList, Comparison<T> IDComparer = null, Comparison<T> lowLevelComparer = null, bool confirmUniqueness = true) where T : IComparable, new()

Admittedly, adding the where clause at the end was in response to the error "cannot create an instance of the type of the variable T because it has no new () constraint." This appeared against the line in the method in which

T lastItem = new T();

However, now, if I try to give him two Lists<string>, he says: " 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MF.Comparers.stepCompare<T>(System.Collections.Generic.List<T>, System.Collections.Generic.List<T>, System.Comparison<T>, System.Comparison<T>, bool)'...

Any way to let this method accept lists, are they string or other classes? Or a shortcut to enter lists of strings into a type to be accepted?

+5
source share
2 answers

, , , new T(). , ( string ..) Activator.CreateInstance<T>() - , IMO ( ) default(T), ( ) NULL, , . , bool , , , .

+6

string new(), no. string , , .

, , lastItem. - , default(T), , .

T, , , Func<T> , . , , T. , .

+8

All Articles