为什么不能将 .NET 委托声明为静态? [英] Why can a .NET delegate not be declared static?
问题描述
当我尝试编译以下内容时:
When I try to compile the following:
public static delegate void MoveDelegate (Actor sender, MoveDirection args);
我收到一条错误消息:修改器 'static' 对该项目无效."
I receive, as an error: "The modifer 'static' is not valid for the this item."
我在一个单独的类中使用一个调用委托的类来实现它.问题是,当我在另一个类中使用单例实例调用委托(从标识符,而不是类型)时,无论出于何种原因,我都不能这样做,即使我声明委托是非静态的.显然,我只能通过类型直接引用它,当且仅当委托是静态的.
I'm implementing this within a singleton, with a separate class which calls the delegate. The problem is that when I use the singleton instance within the other class to call the delegate (from the identifier, not the type), I can't do that for whatever reason, even when I declare the delegate non-static. Obviously, I can only refer to it via the type directly if and only if the delegate is static.
这背后的原因是什么?我使用的是 MonoDevelop 2.4.2.
What is the reasoning behind this? I am using MonoDevelop 2.4.2.
更新
在使用以下代码尝试其中一项建议后:
After trying one of the suggestions with the following code:
public void Move(MoveDirection moveDir)
{
ProcessMove(moveDir);
}
public void ProcessMove(MoveDirection moveDir)
{
Teleporter.MoveMethod mm = new Teleporter.MoveMethod(Move);
moveDelegate(this, moveDir);
}
我收到一个处理错误,指出 MoveMethod 必须是一个类型,而不是一个标识符.
I've received a processing error, which states that the MoveMethod must be a type, and not an identifier.
推荐答案
试试这个:
public delegate void MoveDelegate(object o);
public static MoveDelegate MoveMethod;
所以方法变量可以定义为静态的.关键字 static
对于 delegate
定义没有意义,就像 enum
或 const
定义一样.
So the method-variable can be defined static. The keyword static
has no meaning for the delegate
definition, just like enum
or const
definitions.
如何分配静态方法字段的示例:
An example of how to assign the static method-field:
public class A
{
public delegate void MoveDelegate(object o);
public static MoveDelegate MoveMethod;
}
public class B
{
public static void MoveIt(object o)
{
// Do something
}
}
public class C
{
public void Assign()
{
A.MoveMethod = B.MoveIt;
}
public void DoSomething()
{
if (A.MoveMethod!=null)
A.MoveMethod(new object());
}
}
这篇关于为什么不能将 .NET 委托声明为静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!