简而言之,我想知道为什么以下代码编译并运行。
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args) => Console.WriteLine("Hello World!");
}
}
我对C#的有限知识告诉我创建了一个名为Main的Delegate,由于某种原因,编译器/运行时接受此Delegate作为程序的有效起点。我的理解是否正确?是否有特定原因会使用这样的声明?
我看到了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);
}
}
谢谢。
答案 0 :(得分:5)
public static void Main(string[] args) => Console.WriteLine("Hello World!");
不是委托,因为没有delegate
个关键字。这只是一种方法/功能。它的编写方式只是编写简单方法/函数的简便方法,在C#6中引入。它被称为表达式身体函数。请参阅C# : The New and Improved C# 6.0。