Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

c# - 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);

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.

What is the reasoning behind this? I am using MonoDevelop 2.4.2.

update

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);
}

I've received a processing error, which states that the MoveMethod must be a type, and not an identifier.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

public delegate void MoveDelegate(object o);
public static MoveDelegate MoveMethod;

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()); 
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...