the example looks like this:
interface IA
{
ICollection<IB> Bs {get;set;}
}
interface IB
{
}
public class BBase : IB
{
}
public class ABase : IA
{
public ICollection<BBase> Bs { get; set; }
}
The question is that, when I wanted to implement the interface IA
with BBase
, just as I did in ABase
, an error occured. Is that to say I can only use IB
instead of BBase
to implement the IA
in ABase
?
What you need is to make IA
generic:
interface IA<T> where T : IB
{
ICollection<T> Bs { get; set; }
}
interface IB
{
}
public class BBase : IB
{
}
public class ABase : IA<BBase>
{
public ICollection<BBase> Bs { get; set; }
}
The implementation of an interface should exactly match its definition, so in a non-generic case you are expected to have ICollection<IB> Bs {get;set;}
in ABase
exactly, that is it may accept any of IB
implemetations.
While when the interface is generic ( interface IA<T> where T : IB
), it's implementation should provide any T
satisfying the given constraint (ie here some exact implementation of IB
). Consequently ABase
class becomes generic as well.
For more info read:
You can't implement property by specifying different type for it - see Interfaces (C# Programming Guide) :
To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member
In your particular case you either need to use ICollection<IB>
as a type for property in ABase
or follow Konstantin Vasilcov suggestion to use generic IA<T>
.
If you can't go generic route consider making property in the interface 'get' - only. This way you'll be able to not provide setter in the class and validate all "add to to collection" operations by having custom methods to add item(s) to the collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.