简体   繁体   中英

Using Reflection to Cast Delegate to a Generic

I'm using reflection to invoke a generic method:

public DataTable GetEntityData<T>(string EntitiesType, string Query, int Page, List<string> Columns, string OrderByClause, object[] QueryArgs)
{
    using (var model = new MK3Entities())
    {
        Type ET = GetEntitiesType(EntitiesType);

        MethodInfo method = typeof(MK3Entities).GetMethod("GetEntityData");
        MethodInfo generic = method.MakeGenericMethod(ET);

        var obj = (generic.Invoke(model, new object[] { Query, NUMBEROFWIDGETRESULTS, Page, Columns, OrderByClause, QueryArgs }) as DataTable);

        return obj;
    }
}

The method I'm invoking through reflection here takes in a generic delegate which executes for post processing.

The GetEntityData(reflection invoked) functions takes in a delegate as a parameter method stub and delegate declaration:

public delegate IEnumerable<T> PostProcessing<T>(IEnumerable<T> Source) where T : class;

public DataTable GetEntityData<D>(string Query, int NumbOfResults, int Skip, List<string> Columns, string OrderByClause, object[] QueryArgs, PostProcessing<D> PostDelegate)
       where D : class
{
}

Internal to the first GetEntityData<T> that creates the generic method, I also need to create a generic method as a delegate to pass in as a parameter which is passing variable ET as the type.

Does anyone know how I can do this?

I fixed this by passing the Generic in though reflection The Original GetEntityData now takes in a methodinfo called FormatInfo as a parameter which then binds the generic to they input type ET

Type DelegateParam = typeof(MK3Entities.PostProcessing<>).MakeGenericType(ET);

MethodInfo GenericParam = FormatInfo.MakeGenericMethod(ET);
var Formatter = Delegate.CreateDelegate(DelegateParam, GenericParam);

var obj = (generic.Invoke(model, new object[] { Query, NUMBEROFWIDGETRESULTS, Page, Columns,     OrderByClause, QueryArgs, Formatter }) as DataTable);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM