简体   繁体   中英

in c# how to implement typeof(entity) inside generic class

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.

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 });
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

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, eg by not hard-coding the method name or even by caching the actual methods ( MakeGenericMethod is very slow).

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