将 lambda 表达式附加到 C# 程序的 main 方法的结果是什么?
What is the result of attaching a lambda expresstion to the main method of a C# program?
总之,我想知道为什么下面的代码可以编译运行。
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args) => Console.WriteLine("Hello World!");
}
}
我对 C# 的有限了解告诉我创建了一个名为 Main 的委托,并且出于某种原因 compiler/runtime 接受此委托作为程序的有效起点。我的理解正确吗?使用这样的声明是否有特定原因?
我在查看 Roslyn 源代码时遇到了这个问题,发现 here。
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.CodeAnalysis.CommandLine;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine
{
public class Program
{
public static int Main(string[] args)
=> Main(args, Array.Empty<string>());
public static int Main(string[] args, string[] extraArgs)
=> DesktopBuildClient.Run(args, extraArgs, RequestLanguage.CSharpCompile, Csc.Run, new DesktopAnalyzerAssemblyLoader());
public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader)
=> Csc.Run(args, new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir), textWriter, analyzerLoader);
}
}
谢谢。
public static void Main(string[] args) => Console.WriteLine("Hello World!");
不是委托,因为没有 delegate
关键字。只是一个method/function。它的写法只是C#6引入的shorthand写简单methods/functions的方法,称为表达式体函数。参见 C# : The New and Improved C# 6.0。
总之,我想知道为什么下面的代码可以编译运行。
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args) => Console.WriteLine("Hello World!");
}
}
我对 C# 的有限了解告诉我创建了一个名为 Main 的委托,并且出于某种原因 compiler/runtime 接受此委托作为程序的有效起点。我的理解正确吗?使用这样的声明是否有特定原因?
我在查看 Roslyn 源代码时遇到了这个问题,发现 here。
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.CodeAnalysis.CommandLine;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine
{
public class Program
{
public static int Main(string[] args)
=> Main(args, Array.Empty<string>());
public static int Main(string[] args, string[] extraArgs)
=> DesktopBuildClient.Run(args, extraArgs, RequestLanguage.CSharpCompile, Csc.Run, new DesktopAnalyzerAssemblyLoader());
public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader)
=> Csc.Run(args, new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir), textWriter, analyzerLoader);
}
}
谢谢。
public static void Main(string[] args) => Console.WriteLine("Hello World!");
不是委托,因为没有 delegate
关键字。只是一个method/function。它的写法只是C#6引入的shorthand写简单methods/functions的方法,称为表达式体函数。参见 C# : The New and Improved C# 6.0。