How can global function exist in C#?

前端 未结 7 1520
暖寄归人
暖寄归人 2020-12-29 05:58

How can global function exist in C# when everything is defined inside a class? I was reading the documentation of OpCodes.Call at MSDN, and was surprised to see the followin

相关标签:
7条回答
  • 2020-12-29 06:31

    At the Build 2014 conference it was announced that from Roslyn onwards, you can import static methods from types by the using TypeName; directive, so that instead of having to use System.Math.Min(...) you can do:

    using System.Math;
    ...
    var z = Min(x,y);
    

    Note: by the time of release this became:

    using static System.Math;
    
    0 讨论(0)
  • 2020-12-29 06:32

    Because System.Reflection.Emit.OpCodes.Call isn't about C#. It's about emitting IL opcodes. In IL, there are features that are not available in C#. Global functions is one of those features.

    0 讨论(0)
  • 2020-12-29 06:32

    C# does not support all features of MSIL. Global functions is one of them. VB.Net, F#, IronPython or some other language likley to use this and other features that are not generated by C# compiler.

    0 讨论(0)
  • 2020-12-29 06:38

    I'm just overwriting my previous answer...

    Here is what each look like in IL DASM with their associated codes:

    // Static Method
    IL_0001:  call       void testapp.Form1::Test()
    
    // Instance Method
    IL_0001:  call       instance void testapp.Form1::Test()
    
    // Virtual Method
    IL_0001:  callvirt   instance void testapp.Form1::Test()
    
    // Global Function
    IL_0000:  call       void testapp.Test()
    

    So to answer your question, there isn't a direct way to generate the metadata token in the last method for C#. I had to create the last in C++.

    0 讨论(0)
  • 2020-12-29 06:50

    The documentation you are referring to is for .net. C# does not cater for global functions but .net does.

    0 讨论(0)
  • 2020-12-29 06:51

    You can't have global functions in C#, it's just not part of the language. You have to use a static method on some class of your choosing to get similar functionality.

    However C# is not the only language that uses the CLR. One can write Managed C++, which can have global functions.

    0 讨论(0)
提交回复
热议问题