Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance from generic interfaces

I don't know how to solve a problem with generic interfaces.

Generic interface represents factory for objects:

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

Interface represents factory for computers (Computer class) specyfing general factory:

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

Generic interface represents special factory for objects, which are cloneable (implements interface System.ICloneable):

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

Class represents factory for computers (Computer class) and cloneable objects:

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

}

I get compiler error messages In 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'.  
like image 759
Matt Avatar asked Mar 22 '13 11:03

Matt


3 Answers

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

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

have really been

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

Really, I think this is probably what you're 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();
    }
}

Live example: http://rextester.com/ENLPO67010

like image 161
Jamiec Avatar answered Sep 26 '22 00:09

Jamiec


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

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

You possibly don't want the T type to implement IFactory<T>!

like image 26
Mohammad Dehghan Avatar answered Sep 26 '22 00:09

Mohammad Dehghan


Try this this code block:

class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T>
    where T: ICloneable, IFactory<T>
    {

    }
like image 30
Pieter Geerkens Avatar answered Sep 26 '22 00:09

Pieter Geerkens