How can global function exist in C#?

不羁岁月 提交于 2019-12-18 11:46:15

问题


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 wordings,

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


回答1:


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.




回答2:


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;



回答3:


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.




回答4:


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.




回答5:


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




回答6:


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.




回答7:


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



来源:https://stackoverflow.com/questions/7296106/how-can-global-function-exist-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!