I have the following class:
public class GenericClass<T> : IGenericClass<T> where T : class
{
public GenericClass()
public GenericClass(Entity e)
public IQueryable<T> GenericMethod1()
public IEnumerable<T> GenericMethod2()
public T NonGenericMethod1(T t)
}
The class works great; however I’m starting to run into issues where I have to instantiate another instance of GenericClass for every type T I want to use, and it’s getting a little crazy. Is there some sort of abstraction I can create to simplify this?
I was heading in this direction, but I can’t tell if this is the right choice or if there is a better design pattern I could use; plus, the two invoke calls are not working correctlly at all.
public class TestClass
{
private Type type;
public object Invoke(string method, object obj)
{
type = obj.GetType();
MethodInfo m = typeof(GenericClass<>).GetMethod(method);
var result = new object();
if(m.IsGenericMethod == true)
result = m.MakeGenericMethod(type).Invoke(null, new object[] { obj });
else
result = m.Invoke(null, new object[] { obj });
return result;
}
}
TIA
It’s hard to guess without some implementation of GenericClass… but I see constructors and methods – no properties (and no fields?).
If that’s the case, you may want to make GenericClass a static class with static methods. Then you aren’t allowed to instantiate it and you can call the methods directly from the type:
Called by
Or perhaps there are properties or fields, but they aren’t dependent on T, then you can move the Generic responsibility to the methods instead of the class.
Now you can have an instance, and that instance can handle all of the T’s you want to throw at it.
I apologize for the generic-ness of this answer, however that is due to the generic-ness of the question.