C#delegate因参数传递而感到困惑:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
委托是引用类型,为什么它仍然需要使用ref in font传递才能正常工作,如Attach2,类似于值类型?
从C++经验来看,委托只是一个函数指针,Attach1(Action holder)就像Attach1(Action*holder),原始持有者作为'value'传递,因此没有赋值,而在第二种情况下,Attach2(ref Action) holder)就像Attach1(Action**holder),指针实际传递,因此可以正确操作.但是为什么在.NET中没有任何迹象或暗示?
背景是在NHibernate映射中,因为集合字段在基类中声明并在运行时动态代理.
由于有一些代理类需要在编码期间引用集合字段,因此,当NHiberate使用自己的集合实例重新分配字段时,代理会丢失引用.
尝试使用ref"跟踪"参考,但未通过结果.
有些专家可以帮助解释C#ref关键字和NHiberate集合代理(如果有的话)的根本原因.
谢谢.
class Program
{
static void Main(string[] args)
{
var v = new D();
}
}
class A
{
}
class B : A
{
}
class C
{
public A a = new A();
public Proxy p;
public C()
{
p = new Proxy(ref a);
p.Out();
}
}
class D : C
{
public D()
{
a = new B();
Console.WriteLine(a.GetType().Name);
p.Out();
}
}
class Proxy
{
public A a;
public Proxy(ref A …Run Code Online (Sandbox Code Playgroud)