我可以在集合初始值设定项中插入方法/函数吗?我试图在集合初始化程序中的函数中插入表达式,但类中的变量要求声明它的正文。谢谢。
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; }
}
答案 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
是一个拼写错误