【问题标题】:What is the purpose of the => operator on public fields? [duplicate]=> 运算符在公共字段上的目的是什么? [复制]
【发布时间】:2021-08-28 20:51:22
【问题描述】:

在 C# 类中将 => 运算符与公共字段一起使用的目的是什么?我看到这是在 GitHub 上托管的 eShopOnWeb ASP.NET Core 项目的单元测试代码中完成的。它实际上是一个带有=> 运算符的属性,它引用从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;
        }
    }
}

【问题讨论】:

标签: c# public-fields


【解决方案1】:

参加这个课程:

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 only 属性的简写。

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2017-06-09
    • 2021-03-28
    • 2014-01-15
    相关资源
    最近更新 更多