表达式树不能包含对局部函数的引用
An expression tree may not contain a reference to a local function
Error: An expression tree may not contain a reference to a local function
public void Initialize()
{
CloudStorageProperties ImageFileProperties(string fileName) => _cloudStorage.GetBlob(CloudStorageType.Image, fileName).FileProperties;
Config = new MapperConfiguration(x =>
{
x.CreateMap<Category, CategoryViewModel>()
.ForMember(vm => vm.ImagePath, m => m.MapFrom(src => ImageFileProperties(src.ImageFile.Name).Uri.AbsoluteUri));
});
}
我可以用匿名函数替换本地函数并且它可以工作,但是 re sharper 说我应该将它转换为本地函数。
为什么不允许这样做?
Roslyn 中的 pull request 进行了此更改:
References to local functions are now disallowed in expression trees,
which may or may not change in the future (Previously they were
generated as a reference to a mangled method name, which seemed
wrong). Added a new error for this.
所以这背后的原因是:当您在表达式树中引用一个方法时 - 它表示为具有给定方法名称的 MethodCall
表达式。如果您引用名称为 ImageFileProperties
的局部函数 - 您会期望 MethodCall
具有相同的名称。表达式树的目的是被分析和解构,所以名字在那里很重要。但实际上局部函数被编译为静态函数,名称如 <Initialize>g__ImageFileProperties1_0
(在上面的引文中被称为 "mangled method name" )。出于这个原因,Roslyn 开发人员决定不允许这样做以避免混淆(您在源代码中看到的函数名称和表达式树中的函数名称)。使用匿名函数就没有这样的混淆,所以它们是允许的。
Error: An expression tree may not contain a reference to a local function
public void Initialize()
{
CloudStorageProperties ImageFileProperties(string fileName) => _cloudStorage.GetBlob(CloudStorageType.Image, fileName).FileProperties;
Config = new MapperConfiguration(x =>
{
x.CreateMap<Category, CategoryViewModel>()
.ForMember(vm => vm.ImagePath, m => m.MapFrom(src => ImageFileProperties(src.ImageFile.Name).Uri.AbsoluteUri));
});
}
我可以用匿名函数替换本地函数并且它可以工作,但是 re sharper 说我应该将它转换为本地函数。
为什么不允许这样做?
Roslyn 中的 pull request 进行了此更改:
References to local functions are now disallowed in expression trees, which may or may not change in the future (Previously they were generated as a reference to a mangled method name, which seemed wrong). Added a new error for this.
所以这背后的原因是:当您在表达式树中引用一个方法时 - 它表示为具有给定方法名称的 MethodCall
表达式。如果您引用名称为 ImageFileProperties
的局部函数 - 您会期望 MethodCall
具有相同的名称。表达式树的目的是被分析和解构,所以名字在那里很重要。但实际上局部函数被编译为静态函数,名称如 <Initialize>g__ImageFileProperties1_0
(在上面的引文中被称为 "mangled method name" )。出于这个原因,Roslyn 开发人员决定不允许这样做以避免混淆(您在源代码中看到的函数名称和表达式树中的函数名称)。使用匿名函数就没有这样的混淆,所以它们是允许的。