【问题标题】:How does C# call a method before it has been defined in the program? [closed]C#如何在程序中定义方法之前调用它? [关闭]
【发布时间】:2021-03-09 18:28:11
【问题描述】:

我很惊讶以下代码块仍然执行,尽管编译器尚未定义或知道该方法。我首先在另一个程序中注意到了这一点,然后创建了这个测试用例。果然,它有效。在 python 或 JavaScript 中,情况并非如此。它会抛出一个未定义的函数错误。这就是为什么我总是确保先定义函数,然后调用它。

我做了一些研究,虽然我找不到任何明确提到这种现象的东西,但我怀疑这可能是脚本语言(python、JS)和具有公共语言运行时接口的语言之间的主要区别。也许编译器会遍历所有内容并将其转换为机器代码,然后它在开始执行指令时已经知道其中包含的所有字段、属性和方法。

我走对了吗?

using System;

namespace TestingGround
{
    class Program
    {
        static void Main(string[] args)
        {
            //Method call
            Console.WriteLine(GetSumOfFirstTwoOrDefault(null));  // output: 0
            Console.WriteLine(GetSumOfFirstTwoOrDefault(new int[0]));  // output: 0
            Console.WriteLine(GetSumOfFirstTwoOrDefault(new[] { 3, 5, 5 }));  // output: 8 
            
            //Define Method for returning the sum of the first two integers in a list
            int GetSumOfFirstTwoOrDefault(int[] numbers)
            {
                //normal input 1 x array of numbers
                //normal output 1 x scalar that is the sum of the first two numbers only
                //edge case - if input array null / empty
                //Most concise with non null conditional operator and null condiitonal operator
                //normal implementation if array null handle return 0, if array.length < 2 return 0, else 
                //add array[0] + array[1]

                
                if ((numbers?.Length ?? 0) < 2)
                {
                    return 0;
                }
                return numbers[0] + numbers[1];
            }
                             
            
        }
    }
}

【问题讨论】:

  • C# 是一种编译语言。它首先被编译,然后执行该二进制文件。这是大多数语言的工作方式,直到 Python、Javascript 等。

标签: c# oop methods call clr


【解决方案1】:

这在很大程度上取决于语言。既然你提到了其他几个,让我们来比较一下:

  • C# 不关心成员或类型的声明顺序。只要方法在代码中的当前位置可见,您就可以调用它。在您的情况下,您使用了本地方法。这实际上与在类本身中声明方法相同,只是您只能从一种方法调用它。如果你run your code through the compiler and a decompiler after that,你可以看到本地函数是在类上声明的,只是使用编译器生成的名称。

  • 在 JavaScript 或 Python 中,您必须注意调用函数的位置。当然,在下面的 sn-p 中,事情不会起作用:

    foo()
    
    function foo() {
      console.log('Someone called me!')
    }
    

    这是因为在读取其余部分之前尝试执行第一行。但是,对于更类似于 C# 的代码风格,情况不再是这样了:

    def main():
      foo()
    
    def foo():
      print('Someone called me!')
        main()
    

    现在可以了,因为函数的 content 已被解析,但不会立即执行。当我们结束调用 main 时,foo 函数已定义并可调用。在某种程度上,这也模仿了 C# 的工作方式。编译器将所有内容组装在一起,到代码实际执行时,一切都已经到位并且可以找到。

  • 现在,在 C 或 Pascal 等旧语言中,需要先声明函数,然后才能调用它们。这是因为当时的计算能力很稀缺,单遍编译器——只遍历源代码一次并立即输出对象或汇编代码的编译器——很常见。为了生成函数调用的代码,您需要知道函数接受哪些参数以及返回什么——它的签名。所以在 C 中你会有这样的东西:

    void foo(void); // forward declaration
    
    void main(void) {
      foo();
    }
    
    void foo(void) { // actual implementation
      printf("Someone called me!\n");
    }
    

    这里的原因有点不同,但有点可比。虽然执行行的解释器肯定必须知道它应该调用的函数,但编译器(假设它不能返回)也必须知道。

回到 C#:C# 编译器不是单遍编译器,而是对源代码进行多次传递。至少一次收集所有类型和成员及其各自的可见性(尽管只是声明),并且至少再一次生成实际的 IL 代码。当这种情况发生时,关于哪些名称从哪里可见以及它们是什么的信息已经可以使用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多