Answer the question
In order to leave comments, you need to log in
Autodetection of Generic types within Generic (Get
Hi people!
I always have problems with generic.
There is the following class structure:
class Entity<TId> where TId : struct
{
public virtual TId Id { get; set; }
}
interface IRepository<T, in TId> where T : Entity<TId> where TId : struct
{
T Get(TId id);
IList<T> GetAll(); ...
}
class RepositoryProvider
{
public IRepository<TEntity, TId> GetRepository<TEntity, TId>() where TEntity : Entity<TId> where TId : struct
{ ... }
}
provider.GetRepository<Department>();
provider.GetRepository<Department, int>();
public IRepository<TEntity, TId> GetRepository<TEntity>() where TEntity : Entity<TId> where TId : struct
Answer the question
In order to leave comments, you need to log in
Might help:
RepositoryProvider provider = new RepositoryProvider();
dynamic repo = provider.GetRepository<Entity<int>>();
List<Entity<int>> list = repo.GetAll();
Entity<int> entry = repo.Get(10);
interface Entity { }
class Entity<TId> : Entity
where TId : struct
{
public virtual TId Id { get; set; }
}
interface IRepository<T, in TId>
where T : Entity<TId>
where TId : struct
{
T Get(TId id);
IList<T> GetAll();
}
class Repo<T, TId> : IRepository<T, TId>
where T : Entity<TId>
where TId : struct
{
public T Get(TId id)
{
return default(T);
}
public IList<T> GetAll()
{
return new List<T>();
}
}
class RepositoryProvider
{
public dynamic GetRepository<TEntity>()
where TEntity : Entity
{
Type genericParam = typeof(TEntity).GetGenericArguments()[0];
return Activator.CreateInstance(typeof(Repo<,>).MakeGenericType(typeof(TEntity), genericParam));
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question