问题描述
我知道我可以创建一个方法,如
pre $ private $ T MyFun< T>()
其中T: IMyInterface
{...}
我可以做相反的事吗?实现IMyInterface?具体的用例是我不想允许空值,但我一般很好奇。 解决方案
我知道我可以创建一个方法,如
pre $ private $ T MyFun< T>()
其中T: IMyInterface
{...}
我可以做相反的事吗?实现IMyInterface?具体的用例是我不想允许空值,但我一般很好奇。 解决方案
否,在一般情况下,您不能指定排除列表。但是,为了防止允许Nullable类型,可以使用where T:class约束。因为Nullable是一个结构体,它会产生所需的效果。
编辑:哎呀,看起来我太匆忙了 - 你在问怎么防止任何可以null,或者特别是Nullable,被允许?
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.
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?
这篇关于C#泛型不*实现某些东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!