在初始化时在对象成员上使用“this”关键字

时间:2013-11-02 18:37:47

标签: c# this

我有一个OnBuy和OnSell委托我的items对象,问题是我要复制粘贴一些项目,而不是修改每个OnBuy和OnSell的关键字名称,并尝试使用“this”关键字,我已经将我的函数添加到item类中,但是在复制粘贴后不修改对象名称仍然无法访问它。这是我的代码:

        public static Item item = new Item
        {
            Name = "Item",
            ID = 1,
            Price = 50,
            Info = "Awesome!",
            OnBuy = delegate(Client cli)
            {
                // Invalid
                this.BuyTitle(cli);

                // Still can't change
                this.Name = "AAA";

                return true;
            },
            OnSell = delegate(Client cli)
            {
                // Invalid
                this.SellTitle(cli);

                // Still can't change
                this.Name = "AAA";

                return true;
            }
         }

这是项目类:

    public class Item
    {
        public string Name { get; set; }

        public int ID { get; set; }

        public int Price { get; set; }

        public string Info { get; set; }

        public Func<Client, bool> OnBuy { get; set; }

        public Func<Client, bool> OnSell { get; set; }

        public bool BuyTitle(Client cli)
        {
            ...
        }

        public bool SellTitle(Client cli)
        {
            ...
        }
    }

1 个答案:

答案 0 :(得分:2)

您正在使用对象初始值设定项语法来创建Item的实例。匿名委托不可能使用this,因为对象初始化程序无法引用它正在创建的对象。来自C#规范的第7.6.10.2节:

  

对象初始化程序无法引用它正在初始化的新创建的对象。

我不确定代理是否是最合适的机制,但是如果你仍然想要使用它们,我会创建一个静态方法来创建项目并调用它来初始化静态字段。

以下是您可以做的事情的概述:

public static Item item = CreateItem();

private static Item CreateItem()
{
    var item = new Item() { Name = "Item" };
    item.OnBuy = client => { item.OnBuy(client); item.Name = "AAA" };
    return item;
}
相关问题