1

I have a base class that has methods that use a generic type in C#, I then have other classes that inherit from these, I want to specify the type in the parent class to avoid angle brackets everywhere...

Here's a sample method from my base class class CBaseHome

public List<T> fetchAll<T>(CBaseDb db, bool includeEmpty = true) where T : CBaseTable, new()
{
    List<T> retVal = new List<T>();
    ...
    return retVal;
}

I the have a parent class that inherits from this class, (without overriding this function)

In the class that then consumes this I have the following code...

List<student> students = new limxpoDB.Home.student().fetchAll<student>(db, false);

so the Home.student class here inherits the CBaseHome class, and student inherits the CBaseTable...

I'd like to be able to say in the Home.student class that the only valid generic type for that class is student so that my consuming code looks like...

List<student> students = new limxpoDB.Home.student().fetchAll(db, false);

I realise here that the difference is minute, but I also use this library in some VB>Net code where it looks terrible...

Any ideas?

Thanks

4

1 回答 1

4

Generic type parameters on a method cannot be imposed by a child class. So if I have:

public class Parent {
    public List<T> GetStuff<T>() { ... }
}

I can not do:

public class Child : Parent {
    // This is not legal, and there is no legal equivalent.
    public List<ChildStuff> GetStuff<ChildStuff>() { ... }
}

What you can do is make the parent class generic, rather than it's method:

public class Parent<T> {
    public List<T> GetStuff() { ... }
}

public class Child : Parent<ChildStuff> {
    // GetStuff for Child now automatically returns List<ChildStuff>
}
于 2012-05-09T20:59:30.953 回答