2017-05-28 71 views
5

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)); 
    }); 
} 

参考我可以用匿名函数替换本地功能和它的作品,但重新锐利说我应该把它转换到本地功能。

为什么不允许?

回答

6

这里是罗斯林的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开发人员决定不允许这样做,以免混淆(在源代码中看到的函数的名称和表达式树中函数的名称)。通过匿名功能,不存在这样的混淆,因此它们被允许。