【发布时间】:2016-12-14 18:38:06
【问题描述】:
假设我们有一个非泛型基接口,带有一个泛型继承接口:
public interface IFoo { }
public interface IBar<T, K> : IFoo {
K Do(T t);
}
public class BarImpl : IBar<Type, AnotherType> {
public AnotherType Do(Type type) {
return new AnotherType(type);
}
}
我需要创建一个返回 IFoo 实例的工厂,但使用返回的实例我需要能够调用派生类型 Do(T),这是不可用的。
public class FooFactory() {
IFoo Get() {
// simplified, in reality i am returning the correct
// type by checking the generic interface
// types to get an object from a stored list
// of implementations
return BarImpl();
}
}
// Now in another class
public void DoFoo() {
IFoo iFoo = new FooFactory().Get();
// Need to be able to call iFoo.Do(Type) but cannot
}
我能够让它工作的唯一方法是创建一个动态对象,而不是 IFoo,然后调用 Do() - 这在我的情况下确实有效,但我失去了一些我更喜欢的类型安全性保留。
我的问题是我是否可以重新设计它以便能够访问派生接口方法,同时仍然能够维护 IFoo 的列表(以及随后的工厂方法返回类型)????
【问题讨论】:
-
要么将您的
IFoo Get()转换为BarImpl,要么过度考虑您的设计。除非你变得更具体,否则没什么可说的 -
您的类型是
IFoo;没有可以调用Do的类型安全(这是IBar<T, K>的一部分)。你认为这会如何工作?! -
使用 C# 6.0:
(iFoo as IBar<type1, type2>).Do(typeof(type1)); -
保持类型安全?我在此设计中看不到任何类型安全性。工厂返回
IFoo,因此无法保证返回的类型实现IBar<,>,即使实现了,类型参数是什么。