通用 NOT 约束 where T : !IEnumerable
根据标题,是否可以在 c# 4 中声明类型否定约束?
感兴趣的用例是允许以下重载共存
void doIt<T>(T what){}
void doIt<T>(IEnumerable<T> whats){}
目前存在歧义,因为第一个方法中的 T
可能是 IEnumerable<>
(所以我想指定 T
不应该是 IEnumerable
)
As per the title, is it possible to declare type-negating constraints in c# 4 ?
The use-case of interest was to allow the following overloads to co-exist
void doIt<T>(T what){}
void doIt<T>(IEnumerable<T> whats){}
At the moment there is ambiguity because T
in the first method could be an IEnumerable<>
(so I would like to specify that T
should NOT be IEnumerable
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不 - 在 C# 或 CLR 中都没有这样的概念。
No - there's no such concept either in C# or in the CLR.
我发现自己试图实现评论中提到的相同情况:
我期望以下代码引用第一个方法:
但是它< strong>实际上引用了第二个。
一种解决方案是像这样强制转换参数:
强制转换可能会被另一个重载隐藏:
I found my self trying to implement the same case mentioned in the comments:
I expected the following code to reference the first method:
But it actually references the second one.
One solution is to cast the argument like this:
The cast could be hidden by another overload:
据我所知,这是不可能的。
您可以做的是一些运行时检查:
As far as I know it is not possible to do that.
What you can do is some runtime checking:
其用途之一是选项类型。
运行时检查当然可以工作,但您不会享受到编译时类型检查的好处。
one use for this would be an option type.
runtime checking would of course work but you wouldn't have the benefit of type checking at compile time.
不,但是可以用“is”进行检查,然后进行适当的处理......
No, but it would be possible to check with an "is" and then handle it appropriately...
据我所知,Not 约束是不可能的。您可以使用基类和/或接口来约束泛型。面对导致运行时失败的类似问题,我在泛型要处理的类上实现了一个接口:
或者:
As far as I know a Not contraint is not possible. You CAN use base classes and/or Interfaces to constrain a Generic. Faced with a similar problem leading to runtime failures, I implemented an interface on the classes the Generic was to handle:
alternatively:
您使用约束,以便确保您使用的类型具有一些您想要使用的属性/方法/...。
具有类型否定约束的泛型没有任何意义,因为没有目的知道是否存在您不想使用的某些属性/方法。
You use a constraint so you can ensure the type you use has some properties/methods/... you want to use.
A generic with a type-negating constraint doesn't make any sense, as there is no purpose to know the absence of some properties/methods you do not want to use.