I'm trying to get all the interfaces (they are all open generic) derived from IService that a Random class implements. I'm sure that at least one interface Random is implementing inherits from IService<,> but no items is being added to the iServiceTypeInterfaces list.
I have the following code:
var iServiceTypeInterfaces = new List<Type>();
Type iServiceGeneric = typeof(IService<,>);
foreach(Type i of Random.GetInterfaces())
{
Type currentGenericType = i.GetGenericTypeDefinition();
bool isAssignable = currentGenericType.IsAssignableTo(iServiceGeneric);
if(isAssignable)
{
iServiceTypeInterfaces.Add(i);
}
}
public interface IService<T, TSearcheable>
where T : class
where TSearcheable : class
{
Task<IEnumerable<T>> GetAll(TSearcheable searchObj);
Task<T> GetById(Guid id);
Task Create(T entity);
Task Update(T entity);
Task Delete(T entity);
}
public interface IProjectService<T, TSearcheable> : IService<T, TSearcheable>
where T : class
where TSearcheable : class
{
Task<List<Technology>> GetTechs(List<Guid> ids);
}
IsAssignableToisn't designed to return true for the open typeIProjectService<,>and the open typeIService<,>. After all,IProjectService<T, U>is not assignable toIService<V, W>, whereT,U,V,Ware any type. Yes, that is the question you are asking - you are not asking whetherIProjectService<T, U>is assignable toIService<T, U>(which it is), because both types are open types! There's no information about their type arguments at all.I'd recommend just writing out the logic you want using LINQ. From the interfaces of
Random, you want the generic interfaces:IService<,>, orIService<,>The LINQ is straightforward:
Usage: