Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

c# - Is there a generic type-constraint for "where NOT derived from"?

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 FooGenerators 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use something like the following:

public interface IFooGenerator
{
    Foo GenerateFoo();
}

interface ISerialFooGenerator : IFooGenerator { }

interface IParallelFooGenerator : IFooGenerator { }

public class FooGenerator : ISerialFooGenerator
{
    public Foo GenerateFoo()
    {
        //TODO
        return null;
    }
}

public class ParallelFooGenerator<T> : IParallelFooGenerator
    where T : ISerialFooGenerator, new()
{
    public Foo GenerateFoo()
    {
        //TODO
        return null;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...