主函数的回调函数

3
以下是我的c#代码...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        TestPointer test = new TestPointer();
        test.function1(function2);   // Error here: The name 'function2' does not exist in     current context
    }
}

class TestPointer
{
    private delegate void fPointer(); // point to every functions that it has void as return value and with no input parameter 
    public void function1(fPointer ftr)
    {
        fPointer point = new fPointer(ftr);
        point();
    }

    public void function2()
    {
        Console.WriteLine("Bla");
    }
}

如何在主函数中传递函数引用以调用回调函数?……我是c#的新手


你想达到什么目的?(顺便说一下,这看起来像是C#,而不是C ++。) - Oded
4个回答

3

test.function1(test.function2)应该可以实现。

你还需要:

public delegate void fPointer();

替代

private delegate void fPointer();

啊,你还需要将你的delegate标记为public,这样它才能在类外部使用。现在对我来说,它已经可以编译和运行了。 - Rawling

1

您可以使用一个操作来完成它:

class Program
    {
        static void Main(string[] args)
        {
            TestPointer test = new TestPointer();
            test.function1(() => test.function2());   // Error here: The name 'function2' does not exist in     current context

            Console.ReadLine();
        }
    }

    class TestPointer
    {
        private delegate void fPointer(); // point to every functions that it has void as return value and with no input parameter 
        public void function1(Action ftr)
        {
            ftr();
        }

        public void function2()
        {
            Console.WriteLine("Bla");
        }
    }

1

您的代码存在两个问题:

    TestPointer test = new TestPointer();
    test.function1(function2);   

这里作用域中没有名为function2的变量。你想要做的是像这样调用它:

    test.function1(test.function2);   

test.function2实际上是一个方法组, 在这种情况下,编译器将把它转换为委托。接下来是下一个问题:

private delegate void fPointer(); 
public void function1(fPointer ftr)

你将委托声明为私有的。它应该是公共的。委托是一种特殊类型,但它仍然是一种类型(当您声明function1的参数时,您可以声明它们的变量)。当声明为私有时,该类型对于类TestPointer外部不可见,因此无法用作公共方法的参数。
最后,这不是一个错误,但是您调用委托的方式可以简化:
    ftr();

这是您已经更正的代码:

using System;

class Program
{
    static void Main(string[] args)
    {
        TestPointer test = new TestPointer();
        test.function1(test.function2);   
    }
}

class TestPointer
{
    public delegate void fPointer(); 
    public void function1(fPointer ftr)
    {
        ftr();
    }

    public void function2()
    {
        Console.WriteLine("Bla");
    }
}

0
你需要将function2设为静态的或者传递text.function2

如果你将 function2 设为 static,那么你需要传递 TestPointer.function2。否则,你需要传递 test.function2,而不是 text.funxtion2 - Rawling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接