How can I use interface as a C# generic type constraint?

前端 未结 11 2216
不思量自难忘°
不思量自难忘° 2020-11-27 12:27

Is there a way to get the following function declaration?

public bool Foo() where T : interface;

ie. where T is an interface type

11条回答
  •  孤独总比滥情好
    2020-11-27 12:57

    Solution A: This combination of constraints should guarantee that TInterface is an interface:

    class example
        where TStruct : struct, TInterface
        where TInterface : class
    { }
    

    It requires a single struct TStruct as a Witness to proof that TInterface is a struct.

    You can use single struct as a witness for all your non-generic types:

    struct InterfaceWitness : IA, IB, IC 
    {
        public int DoA() => throw new InvalidOperationException();
        //...
    }
    

    Solution B: If you don't want to make structs as witnesses you can create an interface

    interface ISInterface
        where T : ISInterface
    { }
    

    and use a constraint:

    class example
        where TInterface : ISInterface
    { }
    

    Implementation for interfaces:

    interface IA :ISInterface{ }
    

    This solves some of the problems, but requires trust that noone implements ISInterface for non-interface types, but that is pretty hard to do accidentally.

提交回复
热议问题