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

Che*_*hen 11 .net c# methodimplattribute external-methods

它在MSDN上看起来很酷:

指定声明方法,但其实现在别处提供.

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

public class Program
{
    [MethodImplAttribute(MethodImplOptions.ForwardRef)]
    public static extern void Invoke();

    static void Main(string[] args)
    {
        Invoke();
        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 13

ForwardRef的用法非常类似:

consumer.cs

using System;
using System.Runtime.CompilerServices;

class Foo
{
    [MethodImplAttribute(MethodImplOptions.ForwardRef)]
    static extern void Frob();

    static void Main()
    {
        Frob();
    }
}
Run Code Online (Sandbox Code Playgroud)

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

csc /target:module provider.cs
csc /target:module consumer.cs
link provider.netmodule consumer.netmodule /entry:Foo.Main /subsystem:console /ltcg
Run Code Online (Sandbox Code Playgroud)

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

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


Mar*_*ell 1

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