ForwardRef の使用法は、次のようになります。
consumer.cs
using System;
using System.Runtime.CompilerServices;
class Foo
{
[MethodImplAttribute(MethodImplOptions.ForwardRef)]
static extern void Frob();
static void Main()
{
Frob();
}
}
プロバイダー.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
これは、マネージ モジュールをリンクするリンカのあまり知られていない機能の 1 つを使用します。リンカーは、同じ形状のタイプを一緒にゲル化できます (まったく同じメソッドを持つ必要があるなど)。ForwardRef は、実際に他の場所で実装を提供できるようにするものです。
この例はちょっと無意味ですが、1 つのメソッドが別の言語 (IL など) で実装されると、さらに興味深いことが想像できます。