集合初始化程序中的函数/方法c#

时间:2018-01-06 03:30:27

标签: c# collections expression collection-initializer

我可以在集合初始值设定项中插入方法/函数吗?我试图在集合初始化程序中的函数中插入表达式,但类中的变量要求声明它的正文。谢谢。

            List<demo> ags = new List<demo>()
            {
                new demo { acst = "One", currUpd() = () =>  { intba += totint; } ,  st = 1 < 2},
                new demo { acst = "Two", currUpd() = () =>  { intba += intp; } = 0,  st = 1 < 2 },
                new demo { acst = "Three", currUpd() = () =>  { intba += pp; },  st = 1 < 2 }
            };


            var agss = ags.Select(x => new {acst = x.acst, currUpd = x.currUpd, st = x.st });
            foreach (var item in agss)
            {
                if (item.st == true)
                {
                    item.currUpd();

                }
            }


            public class demo
            {
            public string acst { get; set; }
            public delegate void currUpd() { get; set; }
            public bool st { get; set; }
            }

1 个答案:

答案 0 :(得分:3)

您无法像这样声明委托属性。将其声明为Action而不是:

    public Action currUpd { get; set; }

现在你可以这样做:

List<demo> ags = new List<demo>()
{
    new demo { acst = "One", currUpd = () =>  { intba += totint; } ,  st = 1 < 2},
    new demo { acst = "Two", currUpd = () =>  { intba += intp; },  st = 1 < 2 },
    new demo { acst = "Three", currUpd = () =>  { intba += pp; },  st = 1 < 2 }
};

我认为第二个= 0上的demo是一个拼写错误