为什么不能VB.Net找到一个接口扩展方法? [英] Why can't VB.Net find an extension method on an interface?
问题描述
我有一个C#库,有一个扩展方法,是这样的:
I have a C# library that has an extension method, something like:
public interface ISomething { ... }
public class SomethingA : ISomething { ... }
public class SomethingB : ISomething { ... }
public static class SomethingExtensions
{
public static int ExtensionMethod(this ISomething input, string extra)
{
}
}
扩展工作正常,如果所谓的从C#,但如果所谓的从外部VB.Net应用程序的问题:
The extension works fine if called from C#, but has an issue if called from an external VB.Net application:
Dim something = Me.SomethingManager.GetSomething(key)
Dim result = something.ExtensionMethod("extra")
这编译正常,但在运行时会抛出一个异常:
This compiles fine but throws an exception at run time:
公共件上键入ExtensionMethod'SomethingB'未找到。
Public member 'ExtensionMethod' on type 'SomethingB' not found.
如果该VB.Net改变,显式地类型它的工作界面:
If the VB.Net is changed to explicitly make the type the interface it works:
Dim something as ISomething = Me.SomethingManager.GetSomething(key)
Dim result = something.ExtensionMethod("extra")
为什么呢?为什么界面上的扩展方法的工作,但没有实现它的类?我也有同样的问题,如果我用一个子类?是VB.Net的实施扩展方法不完全?
Why? Why does the extension method work on the interface but not the class that implements it? Would I have the same issue if I used a subclass? Is VB.Net's implementation of extension methods incomplete?
有什么我可以在C#库做,使VB.Net在工作中没有显式接口?
Is there anything I can do in the C# library to make VB.Net work without the explicit interface?
推荐答案
通过选项推断关,这code ...
With Option Infer Off, this code...
Dim something = Me.SomethingManager.GetSomething(key)
Dim result = something.ExtensionMethod("extra")
...是相同的...
...is the same as...
Dim something As Object = Me.SomethingManager.GetSomething(key)
Dim result As Object = something.ExtensionMethod("extra")
由于的东西
的类型是对象
,它找不到扩展方法,因为它不是在类型定义的对象
。
Since something
is of type Object
, it can't find the extension method, since it isn't defined on type Object
.
现在,如果你设置选项推断在
,你会得到相同的结果与C#的 VAR
关键字。类型将自动推断。需要注意的是,这也可能会破坏现有code,但它可以为特定的文件中启用,如选项严格
。
Now, if you set Option Infer On
, you will get the same results as with C#'s var
keyword. Types will be automatically inferred. Note that this could also break existing code, but it can be enabled for a specific file, like Option Strict
.
最好的做法是同时设置选项严格
和选项推断
来开。
The best practice would be to set both Option Strict
and Option Infer
to On.
这篇关于为什么不能VB.Net找到一个接口扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!