c# - 从构造函数中提取继承的类参数
问题描述
首先很抱歉,如果我将使用混乱的术语,我仍然在学习很多关于命令模式和 C# 的知识。
我正在尝试使用 C# 在 Unity3D 中实现命令模式,特别是这个实现重新适应了我的情况。
给定Command.cs和GameController.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
有没有办法提取论点?
解决方案
由于您listOfCommands
是 a Stack
of 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);
}
推荐阅读
- amazon-web-services - 通过 AWS CLI 使用临时安全凭证
- upgrade - 逐步了解我应该如何更新/升级 Zookeeper
- javascript - 如何使用js依赖从dart调用javascript函数
- sdk - gcp 是否有任何 sdk 支持来获取 iam 用户、服务帐户和附加到他们的相应角色的列表?
- c# - Linq to objects 和 lambda 表达式
- mysql - XAMPP MySQL 无法启动
- python - 如何在 Python 3 中导入“gleam”包?
- arrays - 如何在二进制数组中找到孤立的零?
- ios - 领域模型类的问题
- mysql - 如何通过mysql查询从考勤表中获取考勤报告?