Inheritance from common interfaces

I do not know how to solve the problem with common interfaces.

A common interface represents a factory for objects:

interface IFactory<T> { // get created object T Get(); } 

The interface represents a factory for computers (a class of computers) that have the general form of a factory:

 interface IComputerFactory<T> : IFactory<T> where T : Computer { // get created computer new Computer Get(); } 

The common interface is a special factory for objects that are cloned (implements the System.ICloneable interface):

  interface ISpecialFactory<T> where T : ICloneable, IFactory<T> { // get created object T Get(); } 

The class represents a factory for computers (computer class) and cloned objects:

  class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T> { } 

I get compiler error messages in the MyFactory class:

 The type 'T' cannot be used as type parameter 'T' in the generic type or method 'exer.ISpecialFactory<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'exer.IFactory<T>'. The type 'T' cannot be used as type parameter 'T' in the generic type or method 'exer.ISpecialFactory<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.ICloneable'. 
+6
source share
3 answers

Not sure if this is a typo, but if it is:

 interface ISpecialFactory<T> where T : ICloneable, IFactory<T> 

really were

 interface ISpecialFactory<T> : IFactory<T> where T : ICloneable 

Indeed, I think this is probably what you are trying to do:

 public class Computer : ICloneable { public object Clone(){ return new Computer(); } } public interface IFactory<T> { T Get(); } public interface IComputerFactory : IFactory<Computer> { Computer Get(); } public interface ISpecialFactory<T>: IFactory<T> where T : ICloneable { T Get(); } public class MyFactory : IComputerFactory, ISpecialFactory<Computer> { public Computer Get() { return new Computer(); } } 

Real-time example: http://rextester.com/ENLPO67010

+8
source

I think your definition of ISpecialFactory<T> is incorrect. Change it to:

 interface ISpecialFactory<T> : IFactory<T> where T : ICloneable { // get created object T Get(); } 

You may not need type T to implement IFactory<T> !

+3
source

Try this code:

 class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T> where T: ICloneable, IFactory<T> { } 
+2
source

All Articles