パラメーターとして渡す C# デリゲートに混乱しています。
class Program
{
static void Main(string[] args)
{
var a = new A();
Action holder = delegate{};
//a.Attach1(holder); //nothing printed
a.Attach2(ref holder);//print as expected
holder();
}
}
public class A
{
private void P1()
{
Console.WriteLine("Inaccessible");
}
public void P2()
{
Console.WriteLine("Accessible");
}
public void Attach1(Action holder)
{
holder += P1;
holder += P2;
}
public void Attach2(ref Action holder)
{
holder += P1;
holder += P2;
}
}
デリゲートは参照型ですが、Attach2 のように値型のように正しく機能するために、フォントに ref を付けて渡す必要があるのはなぜですか?
C++ の経験から、デリゲートは単なる関数ポインターであり、Attach1(Action ホルダー) は Attach1(Action* ホルダー) のようなものです。元のホルダーは「値」として渡されるため、割り当てられませんが、2 番目のケースでは、Attach2(ref Action holder) は Attach1(Action** holder) のようなもので、実際にポインタが渡されるため、正しく操作できます。しかし、なぜ .NET には指示やヒントがないのですか?