【发布时间】: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 等。