Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在将类插入列表时触发某些代码_C# - Fatal编程技术网

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;