首先,“友好名称”的任何通用解决方案仍然必须使用两种泛型类型进行参数化,所以我认为这不是您要寻找的,因为它不会真正为您节省任何输入。
假设您希望FriendlyName
已经绑定了类型,那么我认为您可以通过使用隐式转换和装饰器模式来获得可行的解决方案。
警告!!!我只是在浏览器中输入了这个(没有 IDE 或编译器),我的 C# 非常生锈,所以这可能需要调整
public interface FooFactory : IGenericFactory<Foo, FooEnum> {
IGenericFactory<Foo, FooEnum> Wrapped { get; }
// The "magic" - Note that magic always makes your code harder to understand...
public static implicit operator FooFactory(IGenericFactory<Foo, FooEnum> wrapped) {
// I think this can be placed here. If C# won't let you add this
// implicit operator here, then you can easily implement this factory
// method as an extension on IGenericFactory<Foo, FooEnum>
return new FooFactoryWrapper(wrapped);
}
public static implicit operator IGenericFactory<Foo, FooEnum>(FooFactory wrapper) {
return wrapper.Wrapped;
}
// I'm pretty sure we can hide this implementation here in the interface,
// but again, my C# is pretty rusty, so you may have to move this
// and/or change the visibility
private class FooFactoryWrapper : FooFactory {
public IGenericFactory<Foo, FooEnum> Wrapped { get; private set; }
public FooFactoryWrapper(IGenericFactory<Foo, FooEnum> wrapped) {
this.wrapped = wrapped;
}
// Since the "friendly type" is still an instance of the base type,
// you'll still have to fully implement that interface. Just delegate
// all calls to your wrapped type (most useless Decorator ever)
public Foo Make() { return Wrapped.Make(); } // sample method in IGenericFactory<>
}
}
现在,您应该可以像这样使用它:
IGenericFactory<Foo, FooEnum> inter = GetTheInterface();
FooFactory fn = inter; // implicit conversion to wrapper type
DoWork(fn); // use the "friendly name" like it were it's wrapped type
// implicit conversion back to wrapped type
public void DoWork(IGenericFactory<Foo, FooEnum> fooFactory) {
...
}
话虽如此,我不会经历这种努力。每当我创建了这样的“友好名称”类型时,我就会将它们作为我的“模型”的一部分并将它们视为正确的类型,这意味着我直接在方法签名和构造函数中请求它们。
像这样的东西:
public interface BarFactory : IGenericFactory<Bar, BarEnum> { }
// Asking for a BarFactory and not a IGenericFactory<Bar, BarEnum>
public void DoWork(BarFactory barFactory) { ... }
打字少得多,也不需要魔法。