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

前端 未结 3 1436
醉话见心
醉话见心 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<T> : IParallelFooGenerator
        where T : ISerialFooGenerator, new()
    {
        public Foo GenerateFoo()
        {
            //TODO
            return null;
        }
    }
    
    0 讨论(0)
  • 2020-12-15 21:32

    The simple answer is no.

    The long answer (still no):

    Microsoft puts it well in their explanation of type constrains: "The compiler must have some guarantee that the operator or method it needs to call will be supported by any type argument that might be specified by client code."

    The fundamental purpose of constraints is not to prohibit certain types from being used, but rather to allow the compiler to know what operators or methods are supported. You can, however, check if a type implements/inherits a specific interface/base class at run-time and throw an exception. With that, though, you will not be able to get a design-time error from intellisense.

    I hope this helps.

    0 讨论(0)
  • 2020-12-15 21:36

    ParallelFooGenerator<ParallelFooGenerator> already isn't possible, because ParallelFooGenerator is a generic type and you didn't specify a generic argument.

    For example, ParallelFooGenerator<ParallelFooGenerator<SomeFooGenerator>> is possible -- and would allowing such a type really be that bad?

    0 讨论(0)
提交回复
热议问题