简体   繁体   English

任何人都知道 IL/CLR 如何准确生成局部函数 C#7

[英]Any one know how exactly IL/CLR generates Local Functions C#7

https://www.infoworld.com/article/3182416/c-7-in-depth-exploring-local-functions.html https://www.infoworld.com/article/3182416/c-7-in-depth-exploring-local-functions.html

I really need to know exactly following code how Local Functions supposed to be.我真的需要确切地知道以下代码应该如何本地函数。

Am 0% IL Code/MSIL experience.我是 0% IL 代码/MSIL 经验。

  public static void Display(string str)
    {
        int ctr = 5;
        DisplayText();

        void DisplayText ()
        {
            for(int i = 0; i < ctr; i++)
            Console.WriteLine(str);
        }
    }

Question I need to know here from previous code:我需要从以前的代码中知道的问题:

  1. If we call main function Display() does Local Function DisplayText() always generated when main one called?如果我们调用主 function Display()本地 Function DisplayText()是否总是在主调用时生成? Or it created as a fake local function in C# but in MSIL it generated as Global function?或者它在 C# 中创建为假的本地 function 但在 MSIL 中它生成为全局 function?
  2. In lamda expression method?在lamda表达法中? does it same above?和上面一样吗?
  3. Is it safe to depend on local functions?依赖本地函数是否安全? or shall we not used it anyway.还是我们无论如何都不要使用它。 (performance maybe idk ) (性能可能idk

Edit:- I think Local Properties (which not exists yet or maybe...).编辑:-我认为本地属性(尚不存在或可能......)。 it is useful also sometimes.它有时也很有用。 which you can have some calculation in same Method as a local property.您可以在与本地属性相同的方法中进行一些计算。 as previous example but DisplayText are property.与前面的示例一样,但 DisplayText 是属性。 Wish they add it also.希望他们也添加它。

CIL and the runtime have no concept of a local function, instead the C# compiler translates it into a normal method with private visibility and potentially a class/struct used to share state with the declaring method. CIL 和运行时没有本地 function 的概念,而是 C# 编译器将其转换为具有私有可见性的普通方法,并且可能是用于与声明方法共享 Z9ED39E2EA931586B6A985A6942EF57EZ 的类/结构。 You can see this for yourself by compiling the code and then decompiling the assembly, or by using a site such as SharpLab.io .您可以通过编译代码然后反编译程序集或使用诸如SharpLab.io 之类的站点来亲自查看这一点。

Lambda expressions and anonymous methods are very similar, except that they need to provide a delegate which can limit the optimization opportunities. Lambda 表达式和匿名方法非常相似,只是它们需要提供一个可以限制优化机会的委托。

The compiler puts a lot of effort into optimizing the generated code, I would not expect local methods to affect performance much beyond what you would get for any other method.编译器在优化生成的代码方面付出了很多努力,我不希望本地方法对性能的影响远远超出任何其他方法所获得的影响。 I would suggest you focus more on how it affects maintainability, at least until you can identify an actual performance problem by profiling.我建议您更多地关注它如何影响可维护性,至少在您可以通过分析确定实际性能问题之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM