在 C# 中实现重写抽象方法的委托
我对 .Net 相当陌生,我显然在这里做错了什么。在我的抽象基类中,我有以下委托:
public delegate bool DEnqueue(ref IPCPriorityMessage item, byte priority);
... 和以下方法声明:
public abstract DEnqueue Enqueue();
在我的实例类中,我有以下内容:
public override DEnqueue Enqueue;
我将 Enqueue 指向适用的本地方法。仅当我不使用继承或不使用委托时,我才能使其正常工作。
我的确切目标是:
- 使用基本抽象类来强制设计模式。实例必须包含方法 Engueue()。
- 在实例类中使用委托,以便在调用公共 Enqueue() 方法时调用适用的私有 enqueue() 方法。
我该怎么做?我尝试使用接口,但基本上有同样的问题。
注意:我只知道在运行时使用哪个私有 enqueue(),因此我使用了委托。
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 my use of delegates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您正在寻找模板方法模式。无需使用代表。
Looks like you're looking for the Template Method Pattern. No need to use delegates.
首先,基类中的方法声明可能没有表达您的想法。它表示
Enqueue
方法返回DEnqueue
类型的委托,而不是该方法与委托具有相同的类型。您可以做的是在基类中拥有一个
DEnqueue
类型的属性:您可以(或者实际上必须)然后使用委托来实现它:
您可以在属性中调用相同的委托就像调用方法一样。
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 typeDEnqueue
, 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:You can (or actually, have to) then implement it using a delegate:
You can call the delegate in the property the same way as you would call a method.