generic NOT constraint where T : !IEnumerable

前端 未结 7 1459
余生分开走
余生分开走 2020-12-03 13:31

As per the title, is it possible to declare type-negating constraints in c# 4 ?

7条回答
  •  孤街浪徒
    2020-12-03 13:57

    I found my self trying to implement the same case mentioned in the comments:

    void doIt(IEnumerable what) { }
    void doIt(T whats) { }
    

    I excepted the following code to reference the first method:

    doIt(new List());
    

    But it actually references the second one.

    One solution is to cast the argument like this:

    doIt(new List().AsEnumerable());
    

    The cast could be hidden by another overload:

    void doIt(List whats) {
        doIt(whats.AsEnumerable());
    }
    

提交回复
热议问题