C# 如何在将类插入列表时触发某些代码
我有这个项目类别:C# 如何在将类插入列表时触发某些代码,c#,C#,我有这个项目类别: public class Item { public string Name; public Entity ItemOwner; public Action<Entity> effect; public Item(string name, Action<Entity> effect) { Name = name;
public class Item
{
public string Name;
public Entity ItemOwner;
public Action<Entity> effect;
public Item(string name, Action<Entity> effect)
{
Name = name;
this.effect = effect;
}
public void Use()
{
effect(ItemOwner);
}
}
我想要这段特定的代码:
Potion.ItemOwner = Player;
当项目放置在实体的库存中时触发
这是可能的吗?我不认为这可以从item类中超级干净地实现。
您可以向
实体
类添加一个函数,如下所示:
public void AddItem(项目){
项目。添加(项目);
item.EntityOwner=此项;
}
类似地,您需要一个removietem
函数来取消设置EntityOwner
如果使用此方法,您可能希望Items
成为protected
变量,以便没有AddItem
函数,其他类无法将项添加到列表中
另一个选项是在项
类中添加OnAddedToList
函数,以代替上面的项。EntityOwner
只需对该项调用added to list函数即可。如果每个项目都有比设置所有者更独特的事情要做,那么这可能就是您想要的
Entity Player = new Entity("Dave", 50, true);
Item Potion = new Item("Healing Potion", ItemOwner => ItemOwner.Health += 25);
Potion.ItemOwner = Player;
Player.Items.Add(Potion);
Player.UseItem("Healing Potion");
Potion.ItemOwner = Player;