gpt4 book ai didi

c# - 通过匿名方法分配匿名类型的属性

转载 作者:可可西里 更新时间:2023-11-01 07:54:40 26 4
gpt4 key购买 nike

我是 C# 函数方面的新手,如果这个问题很蹩脚,我很抱歉。

给定以下错误代码:

var jobSummaries = from job in jobs
where ...
select new
{
ID = job.ID,
Description = job.Description,
FileName = (job) => {
// primitive logic not
// worth to become a named method
try { return job.Files[0].LocalName); }
catch { return null as string; }
}
};

此代码产生以下合理的编译器错误:

cannot assign lambda expression to anonymous type property

上面的代码会将委托(delegate)设置为 FileName 属性。但这不是我的目的。我希望代码像这样工作但不命名方法:

var jobSummaries = from job in jobs
where ...
select new
{
ID = job.ID,
Description = job.Description,
FileName = this.ExtractFileName(job)
};

...
private string ExtractFileName(Job job)
{
try { return Path.GetFileName(job.Files[0].LocalName); }
catch { return null as string; }
}

有什么建议吗?

最佳答案

要直接调用匿名函数,这是可行的:

int result = new Func<int, int>( (int i) =>{ return i + 5; } ).Invoke(3);
// result = 8

但我同意,int result = (i => i + 5)(3); 会更酷 =)

关于c# - 通过匿名方法分配匿名类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2371493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com