2017-05-28 72 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開發人員決定不允許這樣做,以免混淆(在源代碼中看到的函數的名稱和表達式樹中函數的名稱)。通過匿名功能,不存在這樣的混淆,因此它們被允許。