Reputation: 65
Is it possible to change the type of T in a method that takes a generic parameter into any kind of object when inherited. For example, I have this interface:
public interface IMethod
{
void Add<T>(T obj);
List<T> Get<T>();
void Update<T>(T obj);
void Delete<T>(T obj);
}
And I have 4 classes that are Book, Bookcase, Shelf. For each of them I have another class where I implement the methods, so I have the functionality there. Here is the Bookcasecatalog clas.
public class BookcaseCatalog: IMethod
{
private ObservableCollection<Bookcase> obsCase;
public string ConnectionString { get; set; }
public void Add(Bookcase obj)
{
}
public void Add<T>(T obj) where T : Bookcase
{
//Do smth
}
}
And when I'm done here, inherit it the interface in another class and T is a Book for example.
Upvotes: 1
Views: 65
Reputation: 7455
As you have it right now, the user can decide what kind of T he uses when calling the method Add
(your constraint limits that, but thats not the idea of how to use them, they shouldn't be used at implementation.).
If you can, make your interface generic. This will allow you to decide what T is when implementing the class. Example:
public interface IMethod<T>
{
void Add<T>(T obj);
List<T> Get<T>();
void Update<T>(T obj);
void Delete<T>(T obj);
}
This will make all of your T
the same type as the T
in the functions
You can use it like this:
public class BookcaseCatalog: IMethod<Bookcase>
{
private ObservableCollection<Bookcase> obsCase;
public string ConnectionString { get; set; }
public void Add(Bookcase obj)
{
//Do smth
}
}
Upvotes: 2
Reputation: 272760
I think what you need here is a generic interface!
You should change your IMethod
to this:
public interface IMethod<T> {
void Add(T obj);
List<T> Get();
void Update(T obj);
void Delete(T obj);
}
Now you get it? When you implement the interface, you are going to specify a type:
public class BookcaseCatalog : IMethod<Bookcase> {
//...
}
Then all the T's in the interface will be replaced by Bookcase
:
public class Bookcase : IMethod<Bookcase> {
public void Add(Bookcase obj) {/*Do something*/}
public List<Bookcase> Get() {return something}
public void Update(Bookcase obj) {/*Do something*/}
public void Delete(Bookcase obj) {/*Do something*/}
}
That's it!
And I think it's better to learn some terminologies here. IMethod<Bookcase>
is called a closed type, and IMethod<T>
is called an open type.
Please note that if a method needs a parameter of an IMethod<T>
, you can pass it an IMethod<Bookcase>
. But if it wants an IMethod<Bookcase>
, you cannot give it an IMethod<SomethingElse>
. This means that closed types can be converted their open counterparts but closed types cannot be converted to other closed types unless the rules of contra- and co-variance apply.
Upvotes: 0