当参数类型为基类时,将派生类作为参数传递给方法 [英] Passing Derived class as a parameter to a method when the parameter type is base class
问题描述
我是一个新手,正在尝试理解继承和设计模式的概念.
I am a newbie and trying to understand concepts of inheritance and design patterns.
我遇到了这种模式http://en.wikipedia.org/wiki/Strategy_pattern当我浏览一些博客时.
I came across this pattern http://en.wikipedia.org/wiki/Strategy_pattern when I was going through some blog.
我觉得很有趣,想了解更多.所以我开发了以下程序.
I found it interesting and wanted to learn more. So I developed the following program.
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
构造函数期望基类作为参数时,如何将派生类作为参数传递?铸造是否隐含地发生?为什么编译器不报错?
The program compiles fine and is working. But my question is how is it possible to pass derived class as a parameter when the Context
constructor is expecting base class as a parameter? Is the casting happening implicitly? Why does the compiler does not error?
context = new Context(new ConcreteStrategyAdd());
public Context(Strategy strategy)
{
this.strategy = strategy;
}
推荐答案
简单地说:
派生类(或子类)是其基类的实例.
A Derived class (or subclass) is an instance of its base class.
因此,当您将 ConcreteStrategyAdd
的实例传递给构造函数时,您实际上是在传递一个 Strategy
对象.
So, when you pass an instance of ConcreteStrategyAdd
into the constructor, you are essentially passing a Strategy
object in.
不涉及铸造.类型层次结构允许这种类型的编程.它允许程序员在他们的代码中使用多态.
There is no casting involved. The type hierarchy allows for this type of programming. It allows programmers to use polymorphism in their code.
这篇关于当参数类型为基类时,将派生类作为参数传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!