Reputation: 60
what i want to achieve :
Type type = typeof(Entity);
var result =_unitofwork.BaseRepositoryFor<type>.createEntity(entity);
I have tried method info and few more examples but couldnt endup working.
CreateEntity/deleteEntity all back end stuffs are implemented generically butI need to add somehow the type inside my generic method.
what is working fine :
MyDb _db= new MyDb();
private static T entity;
private static BaseRepositoryFor<T>_dynamic_class = new BaseRepository<T>(_db);
var result =_unitofwork.BaseRepositoryFor<T>.createEntity(entity);
But I need to Type object instead of 'T' in my method.
Duplicate ISSUE :I already checked that duplicate question. but it dint actually solved it my problem since i have some extension methods to create/delete/update/get and i need to get those methods name in intelligence.
Upvotes: 0
Views: 166
Reputation: 37000
I believe what you need is MakeGenericType:
var t = typeof(BaseRepositoryFor<>)
Type constructed = t.MakeGenericType(inferedType);
Now you can call the actual method by reflection:
var m = constructed.GetMethod("createEntity");
var result = m.Invoke(null, new[] { entity });
Upvotes: 1
Reputation: 1199
You have to create a generic method in your class. If possible, call it with the generic parameter from outside. Alternatively, you can call the generic method via reflection, however note that this is slow. I give you a very primitive, not very maintainable example below, but you will see the point:
private TEntity MyMethodGeneric<TEntity>(){
return _unitofwork.BaseRepositoryFor<TEntity>.createEntity(entity);
}
private object MyMethod(Type type){
var method = GetType().GetMethod("MyMethodGeneric", BindingFlags.Instance|BindingFlags.NonPublic);
return method.MakeGenericMethod(type).Invoke(this, new object[]{/* if you need to pass parameters}*/);
}
Again, I would try to avoid this if you can. Pass in the generic parameter at a higher level. If you absolutely have to use this pattern, you should see if you can make it better maintainable, e.g. by not hard-coding the method name or even by caching the actual methods (MakeGenericMethod
is very slow).
Upvotes: 0
Reputation: 701
public Type GetSome<T>(T intake)
{
T localT = default(T);
}
I believe that's what you are looking for.
And from the point you can do whatever you need with localT
Upvotes: 0