任何人都可以给我看一个MethodImplOptions.ForwardRef的例子

它在MSDN上看起来很酷:

指定声明方法,但其实现在其他位置提供。

所以我在控制台应用程序中尝试了它:

public class Program { [MethodImplAttribute(MethodImplOptions.ForwardRef)] public static extern void Invoke(); static void Main(string[] args) { Invoke(); Console.Read(); } } 

那我现在该怎么办? 我在哪里可以提供Program.Invoke的实现?

我的理解ForwardRef以与extern相同的方式运行,并且用于在您使用的语言缺乏直接支持时引导运行时(通过C#中的extern )。 因此,用法应该与extern修饰符非常相似,最值得注意的是使用[DllImport(...)]

ForwardRef的用法非常类似:

consumer.cs

 using System; using System.Runtime.CompilerServices; class Foo { [MethodImplAttribute(MethodImplOptions.ForwardRef)] static extern void Frob(); static void Main() { Frob(); } } 

provider.cs

 using System; using System.Runtime.CompilerServices; class Foo { // Need to declare extern constructor because C# would inject one and break things. [MethodImplAttribute(MethodImplOptions.ForwardRef)] public extern Foo(); [MethodImplAttribute(MethodImplOptions.ForwardRef)] static extern void Main(); static void Frob() { Console.WriteLine("Hello!"); } } 

现在神奇的酱汁。 打开Visual Studio命令提示符并键入:

 csc /target:module provider.cs csc /target:module consumer.cs link provider.netmodule consumer.netmodule /entry:Foo.Main /subsystem:console /ltcg 

这使用了一个鲜为人知的链接器function,我们将托管模块链接在一起。 链接器能够将相同形状的类型凝聚在一起(它们需要具有完全相同的方法等)。 ForwardRef实际上允许您在其他地方提供实现。

这个例子有点毫无意义,但如果用不同的语言(例如IL)实现单个方法,你可以想象事情会变得更有趣。