How to execute a callback method instead of an anonymous method?
The following example works, but how can I change it so that instead of executing the anonymous method, it executes my existing callback开发者_开发知识库 method OnCreateOfferComplete()
?
using System;
namespace TestCallBack89393
{
class Program
{
static void Main(string[] args)
{
OfferManager offerManager = new OfferManager();
offerManager.CreateOffer("test", () => Console.WriteLine("finished."));
//offerManager.CreateOffer("test", OnCreateOfferComplete );
//above line gives error: an object reference is required
//for a non-static field...
Console.ReadLine();
}
private void OnCreateOfferComplete()
{
Console.WriteLine("finished");
}
}
public class OfferManager
{
public void CreateOffer(string idCode, Action onComplete)
{
if (onComplete != null)
onComplete();
}
}
}
Make method OnCreateOfferComplete static. This should sove your problem.
Make OnCreateOfferComplete method static.
The problem is that your method OnCreateOfferComplete()
needs to be static
.
The problem is that you are calling CreateOffer from a static method (OnCreateOfferComplete is an instance method).
In this case, just declare your OnCreateOfferComplete
method static.
I think it should be static:
private static void OnCreateOfferComplete()
{
Console.WriteLine("finished");
}
... because you are calling it from the static Main
method.
精彩评论