generic NOT constraint where T : !IEnumerable

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

    As far as I know it is not possible to do that.

    What you can do is some runtime checking:

    public bool MyGenericMethod()
    {
        // if (T is IEnumerable) // don't do this
    
        if (typeof(T).GetInterface("IEnumerable") == null)
            return false;
    
        // ...
    
        return true;
    }
    

提交回复
热议问题