首页 > 解决方案 > 从构造函数中提取继承的类参数

问题描述

首先很抱歉,如果我将使用混乱的术语,我仍然在学习很多关于命令模式和 C# 的知识。

我正在尝试使用 C# 在 Unity3D 中实现命令模式,特别是这个实现重新适应了我的情况。

给定Command.csGameController.cs脚本,我创建了一个DoThing类,继承自Command该类,使用以下代码实现:

public class DoThing : Command
{
    public string name;
    public int healthPoints;

    public DoThing(string name, int healthPoints)
    {
        this.name = name;
        this.healthPoints = healthPoints;
    }
}

现在,由于我通过构造函数(name, healthPoints)将一些参数传递给命令,我想从另一个脚本中提取这些参数。

我尝试(成功)将参数传递给以下行中的命令并将命令保存在堆栈中:

var doCommand = new DoThing("asdf", 123);
Stack<Command> listOfCommands = new Stack<Command>();
listOfCommands.Push(doCommand);

我尝试(成功)在代码执行期间在监视窗口中检索这些参数:

listOfCommands.Peek().name //returns "asdf"

但这在脚本中不起作用,这意味着看不到参数:

Debug.Log(listOfCommands.Peek().name) //throws error

有没有办法提取论点?

标签: c#unity3dcommandcommand-pattern

解决方案


由于您listOfCommands是 a Stackof Command,因此listOfCommands.Peek()返回 aCommand其中没有name变量。您必须检查函数返回的变量的类型并在访问变量之前对其进行转换。

Command command = listOfCommands.Peek();
if(command is DoThing)
{
    Debug.Log(((DoThing) command).name);
}

或更紧凑

if(listOfCommands.Peek() is DoThing doThing)
{
    Debug.Log(doThing.name);
}

或者

DoThing doThing = listOfCommands.Peek() as DoThing;
if(doThing != null)
{
    Debug.Log(doThing.name);
}

推荐阅读