Is there a generic type-constraint for “where NOT derived from”?

前端 未结 3 1445
醉话见心
醉话见心 2020-12-15 20:47

We can specify a \"derived from\" constraint on generic type parameters like this:

class Bar where T : IFooGenerator

Is t

3条回答
  •  执笔经年
    2020-12-15 21:27

    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 : IParallelFooGenerator
        where T : ISerialFooGenerator, new()
    {
        public Foo GenerateFoo()
        {
            //TODO
            return null;
        }
    }
    

提交回复
热议问题