Do generic classes have a base class?
I would like to pass a generic interface to a fun开发者_如何学运维ction:
private I<T> CreateStubRepository<T, I >()
where I : aGenericBaseClass
So i was wondering if generic interfaces implement a base class or specific interface?
I know by using reflection you can test if it is a generic class but I dont see that helping me
Well. What's the point of forcing the usage of any interface? I really do not get it (or your question).
You should more likely do something like this:
public interface IMyRepository<T>
{
}
public class Repository<T> : IMyRepository<T>
{
}
private IMyRepository<TEntity> CreateStubRepository<TEntity>()
{
return new Repository<TEntity>();
}
var repos = CreateStubRepository<User>();
Update
thanks for your answer but thats not what I am asking. What I want to know is does a class that implements a generic interface have a base class or does it inherit from an interface? I dont want to force any interface its more a question of is the object passed generic
Classes do not inherit interfaces. They implement them. The different is subtle but important.
A class can only inherit another class. This means that if you do not specify that a class inherits from another it will still inherit from object. And that wont change no matter how many interfaces a class implement.
class MyClass : ICoolInterface // inherits object
class MyList : ArrayList, ISomeInterface // inherits ArrayList
class MyGenericList<T> : IList<T> // inherits object.
Generic or non-generic classes can implement or inherit from generic or non-generic interfaces and classes. The only limitation is that the full type of any interface/class implemented/inherited from must be discernible given the full type of the class doing the implementing or inheriting. For example, a Foo<Bar> might inherit from FooBase and implement IDisposable; a FnordDuffleBag might inherit from DuffleBag<Fnord> and implement IReachInto<Fnord>.
Thanks for all the comments I think i was going in the wrong direction, What I was hoping for was that when I applied to a class the framework would know that it inherited from a base class or interface of say aGenericItemBaseClass before it constructed the class at runtime.
Yes I know that I can create a generic class with type parameters and use that but thats not what I was asking (although you may have got that impression from my posting).
At runtime I know that when using reflection I can determine if a class is generic by calling : IsGenericType which returns true if a type is generic.
So what I wanted to know which may have been explained poorly is, when using template types is there anyway to determine if that type is a generic type? It appears the answer is No the IL interperates the class as generic not the compiler.
精彩评论