gpt4 book ai didi

c# - 当参数类型是基类时,将派生类作为参数传递给方法

转载 作者:IT王子 更新时间:2023-10-29 03:55:33 25 4
gpt4 key购买 nike

我是新手,正在尝试理解继承和设计模式的概念。

我遇到了这个模式 http://en.wikipedia.org/wiki/Strategy_pattern当我浏览一些博客时。

我觉得很有趣,想了解更多。所以我开发了以下程序。

static void Main(string[] args)
{
Context context;

// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy(3, 4);

context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3, 4);

context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3, 4);

Console.Read();
}

abstract class Strategy
{
public abstract int execute(int a, int b);

public void Test()
{
Console.Write("tttt");
}
}

class ConcreteStrategyAdd : Strategy
{
public override int execute(int a, int b)
{
Console.WriteLine("Called ConcreteStrategyAdd's execute()");
return a + b; // Do an addition with a and b
}
}

class ConcreteStrategySubtract : Strategy
{

public override int execute(int a, int b)
{
Console.WriteLine("Called ConcreteStrategySubtract's execute()");
return a - b; // Do a subtraction with a and b
}
}

class ConcreteStrategyMultiply : Strategy
{
public override int execute(int a, int b)
{
Console.WriteLine("Called ConcreteStrategyMultiply's execute()");
return a * b; // Do a multiplication with a and b
}
}

class Context
{
private Strategy strategy;

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

public int executeStrategy(int a, int b)
{
return strategy.execute(a, b);
}
}

该程序编译良好并且正在运行。但我的问题是,当 Context 构造函数期望基类作为参数时,如何将派生类作为参数传递?类型转换是隐式发生的吗?为什么编译不报错?

context = new Context(new ConcreteStrategyAdd());  

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

最佳答案

不需要强制转换,因为 ConcreteStrategyAdd 是一个 Strategy - 它满足成为 Strategy 的所有要求。这就是多态性的原理。

也许需要一个更简单的例子:

abstract class Fruit { }

class Apple : Fruit { }
class Orange : Fruit { }
class Melon : Fruit { }

class FruitBasket
{
void Add(Fruit item) { ... }
}

FruitBasket basket = new FruitBasket();
basket.Add(new Apple()); // Apple IS A fruit
basket.Add(new Orange()); // Orange IS A fruit
basket.Add(new Melon()); // Melon IS A fruit

class Potato : Vegetable { }

basket.Add(new Potato()); // ERROR! Potato IS NOT A fruit.

关于c# - 当参数类型是基类时,将派生类作为参数传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4595059/

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