We can specify a "derived from" constraint on generic type parameters like this:
class Bar<T> where T : IFooGenerator
Is there a way to specify NOT derived from?
My use-case: I have a bunch of FooGenerator
s that are parallelizable, with the same parallelization code for each, but we don't want them to always be parallelized.
public class FooGenerator : IFooGenerator
{
public Foo GenerateFoo() { ... }
}
Thus, I create a generic container class for generating Foo in parallel:
public class ParallelFooGenerator<T> : IFooGenerator where T : IFooGenerator
{
public Foo GenerateFoo()
{
//Call T.GenerateFoo() a bunch in parallel
}
}
Since I want FooGenerator
and ParallelFooGenerator<FooGenerator>
to be interchangeable, I make ParallelFooGenerator : IFooGenerator
. However, I clearly don't want ParallelFooGenerator<ParallelFooGenerator>
to be legal.
So, as an auxiliary question, is there perhaps a better way to design this if "not derived from" constraints are impossible?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…