[英]How to pass singleton as generic type parameter?
I have an interface of edge: 我有一个边缘界面:
public interface IEdge<TPoint, TFactory>
where TPoint : IPoint
where TFactory : IEdgeFactory<TPoint>
{
TPoint Begin { get; }
TPoint End { get; }
void Divide();
}
The edge can be divided those producing nested edges. 边缘可以分为产生嵌套边缘的边缘。 New edges are created using a factory pattern: 使用工厂模式创建新边:
public interface IEdgeFactory<TPoint>
where TPoint : IPoint
{
IEdge<TPoint> Create(TPoint begin, TPoint end)
}
I want to be able to instantiate a factory inside my IEdge
implementations. 我希望能够在IEdge
实现中实例化一个工厂。 Normally I would do it using ie public static IEdgeFactory<TPoint> Instance { get; }
通常我会使用ie public static IEdgeFactory<TPoint> Instance { get; }
public static IEdgeFactory<TPoint> Instance { get; }
, but I can't define this in interface. public static IEdgeFactory<TPoint> Instance { get; }
,但我不能在接口定义这个。
So is there a way to pass the singleton factory as type parameter and give implementations a way to instantiate it? 那么有没有办法将singleton工厂作为类型参数传递,并为实现提供实例化它的方法?
You can simply pass factory to classes implementing the interface: 您只需将工厂传递给实现该接口的类:
public interface IEdge<TPoint>...
class MyEdge : IEdge<MyPoint>
{
IEdgeFactory<MyPoint> factory;
public MyEdge(IEdgeFactory<MyPoint> factory)
{
this.factory = factory;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.