简体   繁体   English

C#模糊扩展方法

[英]C# ambiguous extension methods

LinqKit has an extension method ForEach for IEnumerable which clashes with System.Collections.Generic.IEnumerable . LinqKit有一个扩展方法ForEach for IEnumerable ,它与System.Collections.Generic.IEnumerable冲突。

Error   4   The call is ambiguous between the following methods or properties: 
'LinqKit.Extensions.ForEach<Domain>(System.Collections.Generic.IEnumerable<Domain>, System.Action<Domain>)' 
and 
'System.Linq.EnumerableExtensionMethods.ForEach<Domain>(System.Collections.Generic.IEnumerable<Domain>, System.Action<Domain>)'

How can I get rid of this error? 我怎样才能摆脱这个错误?

Enumerable , in the framework, does not declare an extension for ForEach() . 在框架中, Enumerable不会为ForEach()声明扩展。 Both of these are from external references. 这两个都来自外部参考。

You should consider only using one of them - either the reference that's adding EnumerableExtensionMethods or the LinqKit . 您应该考虑仅使用其中一个 - 添加EnumerableExtensionMethodsLinqKit

(This, btw, is one reason that using the same namespace as the framework causes problems - in this case, the author of EnumerableExtensionMethods placed it in System.Linq , which is going to cause an issue any time you're using Linq and you have a namespace clash.) (这,顺便说一下,使用与框架相同的命名空间导致问题的一个原因 - 在这种情况下, EnumerableExtensionMethods的作者将它放在System.Linq ,这会在你使用Linq和你的时候引起问题有一个命名空间冲突。)

If you truly need to use this method, then you'll have to call it directly instead of using the extension method, ie: 如果你真的需要使用这个方法,那么你必须直接调用它而不是使用扩展方法,即:

LinqKit.Extensions.ForEach(collection, action);

Or: 要么:

System.Linq.EnumerableExtensionMethods.ForEach(collection, action);

That being said, I would personally just use a foreach loop to process the elements. 话虽这么说,我个人只是使​​用foreach循环来处理元素。

You simply need to fully-qualify the method that you're calling, as in the error message. 您只需要完全限定您正在调用的方法,如错误消息中所示。

So, instead of using 所以,而不是使用

ForEach<Domain>( ... );

use 采用

LinqKit.Extensions.ForEach<Domain>( ... );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM