2016-12-01 7 views
0

をキャストにジェネリックのparam結果を受け取り、クラスを作成し、私はIInfoとそのジェネリック版があります。C#の - コンストラクタ例外

public interface IInfo 
{ 
    IInput Input { get; } 
} 

public interface IInfo<T> : IInfo where T : IInput 
{ 
    new T Input { get; } 
} 

クラスの実装:IINPUTからIOutputを作成するための

public class Info : IInfo<IInput> 
{ 
    public IInput Input { get; }  

    public Info (IInput input) {} 
} 

ファクトリー:

public class GenericFactory<TInput, TOutput> where TInput : IInput where TOutput : IOutput 
{ 
    public IOutput Create(IInfo info) 
    { 
     ConstructorInfo cInfo = typeof(TOutput).GetConstructor(new[] { typeof(IInfo<TInput>) }); 
     object output = cInfo.Invoke(new object[] {cInfo}); 
    } 
} 

上記のコードをテストするには:

public class TestInput : IInput 
{  
} 

public abstract class AbstractOutput<TInput> : IOutput where TInput : IInput 
{  
} 

public class TestOutput: AbstractOutput<TestInput> 
{ 
    public TestOutput(IInfo<TestInput> info) 
    { 

    }  
} 

public void Test() 
{ 
    IInput input = new TestInput(); 
    IInfo info = new Info(input); 

    var factory = new GenericFactory<TestInput, TestOutput>(); 
    IOutput output = factory.Create(info); 
} 

私は次のエラーを取得:

Object of type 'Info' cannot be converted to type'Info<TestInput>'. 

側の注意点を:私は別の方法で/再書き込みのコードを簡素化するための任意の提案に開いています。

+0

_factoryの定義は表示されません。 – mybirthname

+0

var factory = newでなければならないGenericFactory (); – alhazen

答えて

1
public TestOutput(IInfo<TestInput> info) 
{ 

} 

は、明示的にIInfo<TestInput>を期待しています。しかし、IInfo<IInput>(これはInfoのように設計されています)と呼ぶようにしようとしています。

IInput input = new OtherInput(); 
IInfo info = new Info(input); 

var factory = new GenericFactory<TestInput, TestOutput>(); 
IOutput output = factory.Create(info); 

そして今、あなたはあなたはそれができるようにIInfo<T>反変を作成する必要がありますIInfo<TestInput>

を期待して何かにIInfo<OtherInput>を提供してきましたが:それは明確に、あなたも書くことができるようにするに

キャスト:たとえば、

public interface IInfo<in T> : IInfo 
    where T : IInput 
{ 
    //new T Input { get; } 
} 

しかし、それはil contravariantインタフェースを使用している場合はTを返してください。代替方法は、Infoを汎用とし、CreateIInfo<TInput>に変更することです。後者は、実行時エラーではなく、IInfo<OtherInput>Create()に渡そうとすると、コンパイル時エラーの恩恵を受ける

+0

偉大な明確な説明、あなたの時間をありがとう。 – alhazen