9

ジェネリックインターフェイスの問題を解決する方法がわかりません。

ジェネリックインターフェイスは、オブジェクトのファクトリを表します。

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

インターフェイスは、一般的なファクトリを指定するコンピュータ(コンピュータクラス)のファクトリを表します。

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

ジェネリックインターフェイスは、クローン可能なオブジェクトの特別なファクトリを表します(インターフェイスSystem.ICloneableを実装します)。

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

クラスは、コンピューター(コンピュータークラス)およびクローン可能オブジェクトのファクトリを表します。

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

}

MyFactoryクラスでコンパイラエラーメッセージが表示されます。

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'.  
4

3 に答える 3

11

これがタイプミスかどうかはわかりませんが、次のようにする必要があります。

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

本当にされている

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

本当に、これはおそらくあなたがやろうとしていることだと思います:

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();
    }
}

実際の例: http://rextester.com/ENLPO67010

于 2013-03-22T11:19:42.240 に答える
4

ISpecialFactory<T>あなたの定義は間違っていると思います。次のように変更します。

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

Tタイプに実装させたくない場合がありますIFactory<T>

于 2013-03-22T11:22:20.483 に答える
2

このコードブロックを試してください:

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

    }
于 2013-03-22T11:20:40.450 に答える