Suppose I have the following code:
interface IWidget
{
}
interface IWidgetFactory<TWidget>
where TWidget : IWidget
{
}
TWidgetFactory CreateFactory<TWidgetFactory, TWidget>()
where TWidgetFactory : IWidgetFactory<TWidget>
where TWidget : IWidget
{
return ...
}
Whenever I call CreateFactory()
I must pass in both the TWidgetFactory and TWidget type parameters. This seems unnecessary, because TWidgetFactory already has a constraint such that any specialisation of it must already specify TWidget. Is there any way I can have TWidget inferred automatically when calling CreateFactory()
, even if I must add some kind of extra helper methods for it?
(The above is a simple example, but it can get much more complicated in practice, so this could save a lot of complexity.)
Without seeing the body of CreateFactory
, it is difficult to tell what you're doing. Based on the return type, I would suspect CreateFactory
doesn't actually use TWidget
for anything but as the type parameter to the interface. In this case, could you relax your generic constraints a bit?
interface IWidget
{
}
interface IWidgetFactory {} // A new non-generic base interface
interface IWidgetFactory<TWidget> : IWidgetFactory
where TWidget : IWidget
{
}
// Generic constraints wind up not as specific,
// but still provide some level of restriction
// TWidget can no longer be used within this method.
TWidgetFactory CreateFactory<TWidgetFactory>()
where TWidgetFactory : IWidgetFactory
{
return ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.