public 字段上的 => 运算符的目的是什么?
What is the purpose of the => operator on public fields?
在 C# class 中对 public 字段使用 =>
运算符的目的是什么?我在 GitHub 上托管的 eShopOnWeb ASP.NET 核心项目的单元测试代码中看到了这一点。它实际上是一个 属性 和 =>
运算符引用从 getter 方法返回的值吗?有问题的代码如下所示:
using Microsoft.eShopWeb.ApplicationCore.Entities.OrderAggregate;
namespace Microsoft.eShopWeb.UnitTests.Builders
{
public class AddressBuilder
{
private Address _address;
public string TestStreet => "123 Main St.";
public string TestCity => "Kent";
public string TestState => "OH";
public string TestCountry => "USA";
public string TestZipCode => "44240";
public AddressBuilder()
{
_address = WithDefaultValues();
}
public Address Build()
{
return _address;
}
public Address WithDefaultValues()
{
_address = new Address(TestStreet, TestCity, TestState, TestCountry, TestZipCode);
return _address;
}
}
}
拿这个class:
public class Foo
{
public int Bar { get; } = 42;
public int Qaz => 42;
}
反编译后输出如下:
public class Foo
{
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int <Bar>k__BackingField = 42;
public int Bar
{
[CompilerGenerated]
get
{
return <Bar>k__BackingField;
}
}
public int Qaz
{
get
{
return 42;
}
}
}
您正在查看仅 get
个属性的 shorthand。
在 C# class 中对 public 字段使用 =>
运算符的目的是什么?我在 GitHub 上托管的 eShopOnWeb ASP.NET 核心项目的单元测试代码中看到了这一点。它实际上是一个 属性 和 =>
运算符引用从 getter 方法返回的值吗?有问题的代码如下所示:
using Microsoft.eShopWeb.ApplicationCore.Entities.OrderAggregate;
namespace Microsoft.eShopWeb.UnitTests.Builders
{
public class AddressBuilder
{
private Address _address;
public string TestStreet => "123 Main St.";
public string TestCity => "Kent";
public string TestState => "OH";
public string TestCountry => "USA";
public string TestZipCode => "44240";
public AddressBuilder()
{
_address = WithDefaultValues();
}
public Address Build()
{
return _address;
}
public Address WithDefaultValues()
{
_address = new Address(TestStreet, TestCity, TestState, TestCountry, TestZipCode);
return _address;
}
}
}
拿这个class:
public class Foo
{
public int Bar { get; } = 42;
public int Qaz => 42;
}
反编译后输出如下:
public class Foo
{
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly int <Bar>k__BackingField = 42;
public int Bar
{
[CompilerGenerated]
get
{
return <Bar>k__BackingField;
}
}
public int Qaz
{
get
{
return 42;
}
}
}
您正在查看仅 get
个属性的 shorthand。