开发者

C# generic does *not* implement something

I know I can make a method like

private T MyFun<T>() 
  where T : IMyInterface
{...}

Can I do the reverse, i.e. where T does not implement IM开发者_StackOverflow社区yInterface? The specific use case is that I don't want to allow nullables, but I'm curious just in general.


If you don't want nullable types you can do this.

private T MyFun<T>() 
  where T : struct
{...}


No, in the general case you cannot specify an "exclusion list". However, to prevent Nullable types from being allowed, you can use the "where T : class" constraint. Because Nullable is a struct, that will have the desired effect.

Edit: Oops, it appears that I was too hasty - were you asking how to prevent anything that can be null, or specifically Nullable, from being allowed?


You could always just throw a NotSupportedException() at run-time. Admittedly, not as nice as the compiler preventing it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜