C# Generic 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, pages开发者_如何学Goize, pageindex);
}
how do i pass that _type to the generic part??
You have to call the method using reflection. Generics are designed for types which are known at compile-time; you don't know the type at compile-time, therefore you have to jump through some hoops. It'll be something along the lines of:
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's an instance method or a static method, whether it's public or private etc - but the basics are:
- Get the generic method definition
- Construct a method with the right type (effectively: pass the type argument)
- Invoke that constructed method
You may want to cache the generic method definition in a static readonly field, btw - it's reusable.
精彩评论