C# 从主函数回调
下面是我在c#中的代码 如何通过在主函数中传递函数引用来调用回调函数?。。。 我不熟悉c#C# 从主函数回调,c#,C#,下面是我在c#中的代码 如何通过在主函数中传递函数引用来调用回调函数?。。。 我不熟悉c#test。function1(test.function2)应该可以 你还需要 public delegate void fPointer(); 而不是 private delegate void fPointer(); 您需要将功能2设置为静态或传递文本。功能2您可以通过以下操作来完成: class Program { static void Main(string[] arg
test。function1(test.function2)
应该可以
你还需要
public delegate void fPointer();
而不是
private delegate void fPointer();
您需要将
功能2
设置为静态
或传递文本。功能2
您可以通过以下操作来完成:
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");
}
}
您的代码有两个问题:
TestPointer test = new TestPointer();
test.function1(function2);
这里,范围中没有名为function2
的变量。您要做的是这样称呼它:
test.function1(test.function2);
test.function2
实际上是一个函数,在本例中,编译器会将其转换为委托。关于下一个问题:
private delegate void fPointer();
public void function1(fPointer ftr)
您已将委托声明为private。它应该是公开的。A,但它仍然是一种类型(您可以声明它们的变量,这正是您在向function1
声明参数时所做的)。当声明为private时,该类型在类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");
}
}
你想达到什么目标?(这看起来像C,而不是C++,顺便说一下)如果你制作<代码>函数2<代码> >代码>静态<代码>,你将需要通过<代码> TestPosik.Frime2</C>。如果没有,您需要通过
测试。function2
,而不是text.funxtion2
。啊,您必须将您的委托
标记为公共
,以便在课堂外使用。它现在编译并运行良好。
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");
}
}