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

时间:2011-07-26 06:56:48

标签: c# .net methodimplattribute external-methods

MSDN上看起来很酷:

  

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

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

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

    static void Main(string[] args)
    {
        Invoke();
        Console.Read();
    }
}

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

2 个答案:

答案 0 :(得分:13)

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

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

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

答案 1 :(得分:1)

我的理解ForwardRefextern的行为方式相同,用于在您使用的语言缺乏直接支持时指导运行时(通过{在C#中{1}}。因此,使用情况应与the extern modifier非常相似,最明显的是使用extern