gpt4 book ai didi

c# - 调用编译时未指定的方法

转载 作者:行者123 更新时间:2023-11-30 22:04:29 25 4
gpt4 key购买 nike

在 Unity 中进行修补,我有一部分 GUI 会呈现来自代表游戏中不同事物的几种不同类类型之一的信息(例如敌人统计数据)。所有不同的类都有一个方法来创建包含所需信息的信息对象(例如 enemyInfoObject),它有一个根据游戏对象绘制信息的 DrawInfo() 方法。

在我的信息呈现脚本中,我希望能够将任何一个不同的信息对象分配给单个变量(即当前选择的敌人、NPC 等)并能够调用 DrawInfo() 方法.有没有一种干净、简单和/或更好的方法来做到这一点?

如果需要,我可以详细说明。

最佳答案

这是一个著名的设计模式,称为 "Strategy Pattern" .它扩展了“编程到接口(interface)”的思想。

The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

首先,定义一个包含DrawInfo的接口(interface),比如ISprite。您所有的 Sprite 都将是实现此接口(interface)的类。现在游戏可以存储对所选 ISprite 的引用并调用其上的方法。

例如:

public interface ISprite
{
void Draw();
}

public class BossMonster : ISprite
{
public override void Draw()
{
// Draw scary stuff
}
}

public class NPC : ISprite
{
public override void Draw()
{
// Draw stuff
}
}

public class Game
{
private ISprite currentSprite = ...
private List<ISprite> otherSprites = ...

public void Render()
{
currentSprite.Draw();

foreach (ISprite sprite in otherSprites)
{
sprite.Draw();
}
}
}

关于c# - 调用编译时未指定的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25214558/

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