C# generic does *not* implement something

折月煮酒 提交于 2020-02-03 08:04:26

问题


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 IMyInterface? The specific use case is that I don't want to allow nullables, but I'm curious just in general.


回答1:


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?




回答2:


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

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



回答3:


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



来源:https://stackoverflow.com/questions/3842556/c-sharp-generic-does-not-implement-something

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!