Implement a delegate that overrides an abstract method in C#
I am fairly new to .Net, and I am clearly doing something wrong here. In my base abstract class, I have the following delegate:
public delegate bool DEnqueue(ref IPCPriorityMessage item, byte priority);
... and the following method declaration:
public abstract DEnqueue Enqueue();
In my instance class, I have the following:
public override DEnqueue Enqueue;
I point Enqueue to the applicable local method. I can only get this to work if I don't use inheritance or don't use delegates.
My exact objectives are:
- Use the base abstract class to force the design pattern. Instances must contain a method Engueue().
- Use delegates in the instance class so that the applicable private enqueue() method is called when the public Enqueue() method is called.
How do I do this? I tried using interfaces, but has basically the same problem.
NOTE: I only know at runtime which private enqueue() to use, hence开发者_StackOverflow my use of delegates.
Looks like you're looking for the Template Method Pattern. No need to use delegates.
First, the method declaration in your base class probably doesn't say what you think. What it says is that the Enqueue
method returns a delegate of type DEnqueue
, not that the method has the same type as the delegate.
What you could do is to have a property of type DEnqueue
in your base class:
public abstract DEnqueue Enqueue { get; }
You can (or actually, have to) then implement it using a delegate:
private DEnqueue m_enqueue;
public override DEnqueue Enqueue
{
get { return m_enqueue; }
}
You can call the delegate in the property the same way as you would call a method.
精彩评论