将回调传递给类

jim*_*les 2 c# delegates

我有一个类,我想存储一个函数调用.此函数调用可以由类调用,但由父类设置.我想从外部提供要做的调用,包括任何参数.

就像是...

public class TestDelegate
{
    public TestDelegate()
    {
        TestClass tc = new TestClass(DoSomething("blabla", 123, null));
    }

    private void DoSomething(string aString, int anInt, object somethingElse)
    {
        ...
    }
}

public class TestClass
{
    public TestClass(delegate method)
    {
        this.MethodToCall = method;
        this.MethodToCall.Execute();
    }

    public delegate MethodToCall { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

TestClass类初始化它将调用父类的方法的DoSomething用指定参数.我还要提一下,我不想为所调用的方法要求相同的方法签名.意义并不总是(string,int,object)

cdh*_*wie 5

使用Action委托类型并从闭包创建一个这样的实例:

public class TestClass
{
    public TestClass(Action method)
    {
        MethodToCall = method;
        method();
    }

    public Action MethodToCall { get; set; }
}

public class TestDelegate
{
    public TestDelegate()
    {
        // Uses lambda syntax to create a closure that will be represented in
        // a delegate object and passed to the TestClass constructor.

        TestClass tc = new TestClass(() => DoSomething("blabla", 123, null));
    }

    private void DoSomething(string aString, int anInt, object somethingElse)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)