gpt4 book ai didi

c# - 接口(interface)中具有不同参数的策略模式 (C#)

转载 作者:太空狗 更新时间:2023-10-29 19:50:11 24 4
gpt4 key购买 nike

我基本上是在尝试实现一个策略模式,但我想将不同的参数传递给“接口(interface)”实现(从同一对象继承)并且不知道这是否可能。也许我选择了错误的模式,我得到了类似于

的错误

“StrategyA”没有实现继承的抽象成员“void DoSomething(BaseObject)”

使用以下代码:

abstract class Strategy
{
public abstract void DoSomething(BaseObject object);
}

class StrategyA : Strategy
{
public override void DoSomething(ObjectA objectA)
{
// . . .
}
}

class StrategyB : Strategy
{
public override void DoSomething(ObjectB objectB)
{
// . . .
}
}

abstract class BaseObject
{
}

class ObjectA : BaseObject
{
// add to BaseObject
}

class ObjectB : BaseObject
{
// add to BaseObject
}

class Context
{
private Strategy _strategy;

// Constructor
public Context(Strategy strategy)
{
this._strategy = strategy;
}

// i may lose addtions to BaseObject doing this "downcasting" anyways?
public void ContextInterface(BaseObject obj)
{
_strategy.DoSomething(obj);
}

}

最佳答案

听起来您实际上是在尝试重新发明 Visitor pattern ,而不仅仅是按照预期的方式使用策略模式。

此外,由于您使用的是 C#,我建议您阅读 Judith Bishop 的论文,标题为 On the Efficiency of Design Patterns Implemented in C# 3.0 .这详细介绍了访问者模式的多种方法,并且有一些有趣的、相关的有用想法。

关于c# - 接口(interface)中具有不同参数的策略模式 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1959127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com