开发者

How can global function exist in C#?

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 following w开发者_StackOverflow社区ordings,

The metadata token carries sufficient information to determine whether the call is to a static method, an instance method, a virtual method, or a global function.

Global function? Does it exist in C#? (It definitely doesn't refer to static method, as it's explicitly listed along with global function).


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.


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;


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.


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


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++.


I suppose that the thing is, that this is IL injection operation, but IL is not absolutely only about C#. In other words it's for support of the language that supports global functions.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜