Razor Pages(.NET Core2.0)Program.cs中Lambda表达式用法解析
Hey there! Let's break down this Lambda expression confusion step by step—since you're new to C# and Razor Pages, this syntax can feel overwhelming at first, but it's just a handy shorthand for writing cleaner code.
First, let's look at the code you're confused about:
public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }
What this Lambda is actually doing
The => syntax in the BuildWebHost method is called an expression-bodied member, a feature introduced in C# 6. It's a simplified way to write a method that only has one return statement. Let's rewrite it using the traditional method syntax you might be more familiar with:
public static IWebHost BuildWebHost(string[] args) { // The Lambda replaces the curly braces and explicit return keyword return WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }
See? It's exactly the same logic—just shorter. The Lambda here acts as the body of the BuildWebHost method, directly returning the configured IWebHost instance without extra boilerplate.
Why it's related to anonymous functions/delegates
Now, to your question about why this ties to anonymous functions or delegates:
- Lambda expressions in C# are fundamentally shorthand for creating anonymous functions. While this specific use case (expression-bodied method) isn't creating a standalone delegate instance, it's rooted in the same delegate-based concept.
- Think of it this way: you could take the exact same Lambda logic and turn it into an explicit delegate. For example:
Here, the Lambda is directly creating an anonymous delegate. Your original code uses the same Lambda syntax, but instead of assigning it to a delegate variable, it's using it as the implementation of a named method (// Define a delegate type that accepts string[] and returns IWebHost Func<string[], IWebHost> buildHostDelegate = args => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build();BuildWebHost). - Under the hood, both approaches rely on C#'s delegate system. The expression-bodied method is just a compiler shortcut that lets you write simple return-focused methods without the clutter of curly braces and
return.
In the context of .NET Core 2.0 Razor Pages
This syntax is super common in .NET Core startup code because it keeps configuration concise. The BuildWebHost method's job is to set up the web host with default settings, hook up your Startup class (where you configure services and middleware), and return a ready-to-run host. The Lambda makes this one-line core logic easy to read at a glance.
Hopefully that clears up why this Lambda is linked to anonymous functions/delegates, and how it's working in your Razor Pages project!
内容的提问来源于stack exchange,提问作者bits-bytes

