[英]C# Replacing an Object in a class of Objects dynamically ~
我想這是我關於同一主題的第二篇文章,有點...
無論如何,我想通過傳遞AI行為來替換或添加以動態更新代理AIbundles類:
* 不起作用的代碼
public class agent
{
AIbundles = new AIbundle();
public void UpdateBehavior (object Behavior)
{
object CastedBehavior = (Behavior.type) Behavior; //Cast
this.agent.AIbundles.(Behavior.type) = CastedBehavior;
}
}
我的AIbundles類的示例(極其簡化)
public class AIbundles
{
ExampleBehavior1 ExampleBehavior1;
ExampleBehavior2 ExampleBehavior2;
ExampleBehavior3 ExampleBehavior3;
AIbundles()
{
ExampleBehavior1 = new ExampleBehavior1();
ExampleBehavior2 = new ExampleBehavior2();
ExampleBehavior3 = new ExampleBehavior3();
}
}
可悲的是,我很清楚這是一種非常糟糕的實現方式,是否有更好的動態處理對象的方式?
在我看來,您的ExampleBehavior
類應該擴展某些基本類型(是抽象類還是接口取決於您的情況)。 讓我們將基本類型稱為BehaviorBase
。 然后你AIBundle
類應該有類型的屬性BehaviorBase
叫Behavior
,你可以做這樣的事情,沒有任何類型的鑄造:
public void UpdateBehavior(BehaviorBase behavior) {
this.agent.AIbundles.Behavior = behavior;
}
您會這樣稱呼:
var agent = ...;
var someAIThing = initWithAgent(agent);
BehaviorBase behavior = ...;
someAIThing.UpdateBehavior(behavior);
在這一點上,我將強烈考慮消除UpdateBehavior
方法,並直接將行為直接分配給屬性:
var agent = ...;
var someAIThing = initWithAgent(agent);
BehaviorBase behavior = ...;
agent.AIBundles.Behavior = behavior;
也許您不應該在“集合”之類的類中創建每種類型的屬性。 如果要按名稱檢索正確的行為,請改用Dictionary。 或者只是一個行為列表。 如果需要,每個行為都可以具有諸如name或type屬性之類的標識。 您也可以只具有IBehavior接口,該接口具有常用的方法...
我認為這樣的事情可能會對您有用:
public class AIbundles
{
public Dictionary<string, IExampleBehavior> ExampleBehaviors { get; set; }
public AIbundles()
{
this.ExampleBehaviors = new Dictionary<string, IExampleBehavior>();
}
}
public class agent {
AIbundles bundles = new AIbundles();
public void UpdateBehavior (IExampleBehavior behavior)
{
this.bundles.ExampleBehaviors[behavior.Name] = behavior;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.