C# 是否可以在多个级别上传递代理?

C# 是否可以在多个级别上传递代理?,c#,.net,delegates,C#,.net,Delegates,我想做一些类似的事情: class A { void Print(string message) { Console.WriteLine("Hi!"); } B.Method1(Print); } class B { delegate void Print(string message); void Method1(Print PrintOutput) { C.Method2(Prin

我想做一些类似的事情:

class A
{
     void Print(string message)
     {
         Console.WriteLine("Hi!");
     }
     B.Method1(Print);

}

class B
{
     delegate void Print(string message);

     void Method1(Print PrintOutput)
     {
         C.Method2(PrintOutput);
     }   
}

class C
{
     delegate void Print(string message);

     void Method2(Print PrintOutput)
     {
         PrintOutput("Bye!");
     }   
}
我尝试这样做的原因是,我的第一个类(A)是WinForms应用程序中的一个类,它从不同项目的类调用一个方法,但在相同的解决方案中,它反过来从同一解决方案中的另一个类(同样是不同的项目)调用另一个方法。我想从类C调用类a中的方法


如果我尝试按照上面所写的方式执行此操作,我会在类B中收到一个编译错误,表示此方法的最佳重载匹配具有一些无效参数

您会收到错误消息,因为您使用相同的签名声明了两种不同的委托类型,然后您尝试访问
C.Method2
,并在
class B

为了避免这种情况,您必须明确声明类
B
中接受的委托类型是
C
类型:

public void Method1(C.Print PrintOutput)
{
    var C = new C();
    C.Method2(PrintOutput);
}
或者,更好的方法是接受一般的
操作
,而不是创建自己的操作:

class B
{
     public void Method1(Action<string> PrintOutput)
     {
         var C = new C();
         C.Method2(PrintOutput);
     }
}

class C
{
     public void Method2(Action<string> PrintOutput)
     {
         PrintOutput("Bye!");
     }   
}
B类
{
公共无效方法1(操作打印输出)
{
var C=新的C();
C.Method2(打印输出);
}
}
C类
{
公共无效方法2(操作打印输出)
{
打印输出(“再见!”);
}   
}

我想也许动作代表就是你要找的:

public class A
{
    void Print(string message)
    {
        Console.WriteLine("Hi!");
    }

    public A()
    {
        new B().Method1(Print);
    }
}

public class B
{
    public void Method1(Action<string> PrintOutput)
    {
        new C().Method2(PrintOutput);
    }
}

public class C
{
    public void Method2(Action<string> PrintOutput)
    {
        PrintOutput("Bye!");
    }
}
公共A类
{
无效打印(字符串消息)
{
控制台。WriteLine(“嗨!”);
}
公共A()
{
新的B()方法1(打印);
}
}
公共B级
{
公共无效方法1(操作打印输出)
{
新的C()方法2(打印输出);
}
}
公共C类
{
公共无效方法2(操作打印输出)
{
打印输出(“再见!”);
}
}

为什么要在两个类中声明委托?如果建议在类C中使用类似void Method2(B.Print PrintOutput)的方法,那么很遗憾,我无法添加对类B所属项目的引用。为什么要声明委托?为什么不使用内置的
操作
委托?因为我不知道操作:)谢谢!非常感谢。事实上,Action是我一直在寻找的,但我不知道它的存在:)
Action
不是一个关键字,它只是一个和其他类型一样的委托类型。是的,我的错…抱歉:s