我正在尝试按照标题所示进行操作,但是我感到困惑。
我知道委托应该如何工作,但 Visual Studio 告诉我我错了。说明如何执行此操作的 Microsoft 文档包含一个复杂的示例,该示例使用了一个书店程序,该程序包含模板和一堆难以理解的逻辑代码。
你怎么做到这一点?谢谢。
我正在尝试按照标题所示进行操作,但是我感到困惑。
我知道委托应该如何工作,但 Visual Studio 告诉我我错了。说明如何执行此操作的 Microsoft 文档包含一个复杂的示例,该示例使用了一个书店程序,该程序包含模板和一堆难以理解的逻辑代码。
你怎么做到这一点?谢谢。
在您的示例中,我假设您希望该SetGameAreaWithCallback
方法实际调用.changeGameArea
Game1
为此,您需要创建您的委托实例,以便它引用该方法:
// game1 is the instance of the Game1 class that you want to call
// Instantiate the handler
SetGameAreaDelegate handler = new SetGameAreaDelegate(game1.changeGameArea);
如果您使用的是 C#2 或更高版本,则语法会更简单:
// game1 is the instance of the Game1 class that you want to call
// Instantiate the handler
SetGameAreaDelegate handler = game1.changeGameArea;
委托是一个安全的函数指针,您应该将方法分配给该名称的已声明变量,而不是尝试分配您正在执行的类型本身。
class MyGameClass
{
SetGameAreaDelegate handler;
MyGameClass()
{
// Instantiate the handler (since my callback is a non-static method)
// You'll need to preform this assignment in the constructor, 'this'
// is not valid during initialization
handler = new SetGameAreaDelegate(myGameAreaWithCallback);
handler = MyGameAreaWithCallback; // short for above
}
void MyGameAreaWithCallback(Game1.gameAreas newArea)
{
//...
}
}
委托是函数指针的托管包装器。它有自己的类型签名,可能是原始函数指针的保存替代方案。委托可以持有对实例对象的引用,例如 C++ 风格的成员函数指针,但您不必担心这一点,因为运行时会为您计算出此类信息。
知道非静态方法的委托将跟踪对该对象的引用可能会很好。这可能导致内存不会被垃圾回收,因为委托虽然看起来无害,但会维护或跟踪对象引用。
您的代码的问题是类型签名...
void SetGameAreaWithCallback(Game1.gameAreas newArea, SetGameAreaDelegate callback)
...与您的委托类型不匹配...
delegate void SetGameAreaDelegate(Game1.gameAreas newArea);
...为此工作...
SetGameAreaDelegate handler = SetGameAreaWithCallback;
...你的代表应该是...
delegate void SetGameAreaDelegate(Game1.gameAreas newArea, SetGameAreaDelegate callback);
...如果这是您真正的意思,您忘记了一个参数,这就是方法解析失败的原因。