C # General question

I have this function

public DataSet Fetch(string EntityName, ObjectParameter[] parameters, int pagesize, int pageindex)
    {
        Assembly asm = Assembly.Load("NCR.WO.PLU.ItemEDM");
        Type _type = asm.GetTypes().Where(t => t.Name.Equals(EntityName)).ToList().FirstOrDefault();

        object obj = Activator.CreateInstance(_type);

        return DataPortalFetch<???>(parameters, pagesize, pageindex);
    }

      

how to pass this _type to the general part?

+2


source to share


1 answer


You must call the method using reflection. Generics are for types that are known at compile time; you don't know the type at compile time, so you have to jump over a few hoops. It will be something like:

MethodInfo method = typeof(WhateverClass).GetMethod("DataPortalFetch");
MethodInfo constructed = method.MakeGenericMethod(new Type[] { _type });
return constructed.Invoke(this, new object[] {parameters, pagesize, pageindex});

      

The details will depend on whether it is an instance method or a static method, public or private, etc., but the basics are:



  • Get the definition of a generic method
  • Construct a method with the correct type (efficiently: pass a type argument)
  • Call this constructed method

You may want to cache the generic method definition in a static field readonly, btw - it reusable.

+7


source







All Articles