传递多个通用接口的方法 [英] Passing multiple generic interfaces to a method
问题描述
我试图传递多个通用接口作为参数传递给我的一个类的构造函数。
I am trying to pass multiple generic interfaces as parameters to the constructor of one of my classes.
下面的代码无法编译:
public interface IPosterGenerator<T>
{
IQueryable<T> GetPosters();
}
public class Pinboard
{
public Pinboard(IPosterGenerator<A> firstPosterGenerator, IPosterGenerator<B> secondPosterGenerator, IPosterGenerator<B> thirdPosterGenerator)
{
}
}
我有一百个不同类型的海报发电机。他们都从IPosterGenerator接口继承。当我实例化一个新的插件板,我需要三IPosterGenerators传递给插件板的构造。然而,每一个这三个IPosterGenerators将是不同类型的。这就是为什么我来到了这个傻A,B和C。
I have about a hundred different types of poster generators. They all inherit from the IPosterGenerator interface. When I instantiate a new Pinboard, I need to pass three IPosterGenerators to the pinboard's constructor. However, every of these three IPosterGenerators will be of a different type. That's why I came up with this silly A, B and C.
可以这样可言呢?
推荐答案
这听起来像你可能想使插件板
通用:
It sounds like you probably want to make Pinboard
generic:
public class Pinboard<T1, T2, T3>
{
public Pinboard(IPosterGenerator<T1> generator1,
IPosterGenerator<T2> generator2,
IPosterGenerator<T3> generator3)
{
...
}
}
要使它更容易调用,您可以的也的创建一个非泛型类与泛型方法:
To make it easier to call, you can also create a non-generic class with a generic method:
public static class Pinboard
{
public static Pinboard<T1, T2, T3> Create(IPosterGenerator<T1> generator1,
IPosterGenerator<T2> generator2,
IPosterGenerator<T3> generator3)
{
return new Pinboard<T1, T2, T3>(generator1, generator2, generator3);
}
}
然后,如果你已经有了发电机,你可以叫:
Then if you've already got the generators, you can just call:
// Or whatever...
var board = Pinboard.Create(bigGenerator, smallGenerator, mediumGenerator);
这篇关于传递多个通用接口的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!