generic NOT constraint where T : !IEnumerable

前端 未结 7 1456
余生分开走
余生分开走 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:39

    one use for this would be an option type.

    public class Option 
    where A : !B
    where B : !A
    {
        private readonly A a;
        private readonly B b;
    
        private Option(){}
    
        public Option(A a) 
        {
            this.a = a
        }
    
        public Option(B b)  
        {
            this.b = b
        }
    } 
    

    runtime checking would of course work but you wouldn't have the benefit of type checking at compile time.

提交回复
热议问题