我有IInfo
它的通用版本:
public interface IInfo
{
IInput Input { get; }
}
public interface IInfo<T> : IInfo where T : IInput
{
new T Input { get; }
}
类的实现:
public class Info : IInfo<IInput>
{
public IInput Input { get; }
public Info (IInput input) {}
}
从IInput创建IOutput的工厂:
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>'.
旁注:我乐于接受任何以不同方式简化/重新编写代码的建议。
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<OtherInput>
了期望的东西IInfo<TestInput>
您需要进行IInfo<T>
逆向转换才能进行强制转换,例如:
public interface IInfo<in T> : IInfo
where T : IInput
{
//new T Input { get; }
}
但是请注意,T
使用逆向接口返回时是非法的。另一种方法是使Info
通用,然后更改Create
为接受IInfo<TInput>
。在尝试传递IInfo<OtherInput>
给时Create()
,后者会为您带来编译时错误的好处,而不是运行时错误
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句