mardi 14 février 2017

How yo use Type.GetType() to pass an unknown type at runtime to a Generic Method

There is a slight possibility I could have worded the title incorrectly and I apologize if this comes across as already answered (and I just have not found it).

Having said that I have searched this site for several hours and have come across several very involved attempts (not clear enough) of using reflection, which I don't want to use because of performance reasons. I am already using Type.GetType() which searches through the .dll to find the type.

So, without further ado, here goes..

I have a method in a class that accepts a generic type:

public class SomeClass
{
    public TList Execute<TList, TItem>(string text)
        where TList : ICollection<TItem>, new()
        where TItem : new()
    {
        TList list = new TList();
        TItem item = new TItem();
        ...set properties and add to list...
        ...implementation not important...
        return list;
    }
}

Usage (calling method):

public void callingMethod(string typeNameString, string typeItemNameString)
{
    Type T = Type.GetType(typeNameString);
    Type Ti = Type.GetType(typeItemNameString);

    SomeClass sc = new SomeClass();

    // and here is where things falls apart drastically..
    // not sure exactly what to do here as it seems noting works
    var result = sc.Execute<T,Ti>("hello text"); //no luck..'T' is a variable but used as a type
    var result = sc.Execute<Type.GetType(typeNameString),Ti>("hello text"); //no luck...operator '<' cannot be appliedto operands of type 'method group' and 'Type'

    //This works fine
    List<Invoice> _invoices = sc.Execute<Invoices, Invoice>("hello text");
}

public class Invoice
{ //properties omitted }

public class Invoices : List<Invoice>
{}

This seems like a very straight forward/logical approach, but is proving not to be the case.

What am I missing?

I appreciate the time and dedication individuals take to respond to questions on this forum.





Aucun commentaire:

Enregistrer un commentaire