C # generics interface solution
I have an interface named Man
. In this interface, I have a method getList()
that returns a list of type T (depends on the class that implements the interface). I have 3 classes that implement Man
: small
, normal
and big
. Each class has a getList()
thart method that returns a list small
or a list normal
or a list big
.
interface Man<T>{
List<T>getList();
}
class small : Man<small>{
List<small> getList(){
return new List<small>();
}
}
class normal : Man<normal>{
List<normal> getList(){
return new List<normal>();
}
}
class big : Man<big>{
List<big> getList(){
return new List<big>();
}
}
Now I have a class: Home
which contains a parameter bed
, an instance Man
.
bed
can be of different types: small
, normal
, big
. How can I declare a type parameter for bed
?
class Home{
Man bed<> // what i must insert between '<' and '>'??
}
source to share
You also need to do Home
generic:
class Home<T>
{
Man<T> bed;
Edit in response to comments:
If you don't know what type "Man" will exist, another option would be for your generic class to implement a non-generic interface:
public interface IBed { // bed related things here
public class Man<T> : IBed
{
// Man + Bed related stuff...
class Home
{
IBed bed; // Use the interface
Then you can develop against the general contract defined by the interface and allow any type IBed
to be used in Home
.
On the unrelated side of the note, I would recommend using the best naming schemes here - the names don't make much sense ... Why is "Man" called "bed"? You can also view standard Capitalization Agreements .
source to share
I can't pinpoint exactly what you're asking, so I'm going to conclude that it's hard for you to figure out how to set the "bed size" parameter for a home.
This is probably best solved using an Enum. Thus, you can have one object that describes the size of the bed.
public interface IBed
{
BedSize BedSize { get; set; }
}
public enum BedSize
{
Small,
Medium,
Large
}
public class House : IBed
{
public BedSize BedSize { get; set; }
}
This reduces the difficulty of determining the size of the bed later, so you don't have to do reflections or anything nasty.
source to share