【问题标题】:C#9 record doesn't instantiate field variable when record is instantiated [duplicate]实例化记录时,C#9 记录不实例化字段变量 [重复]
【发布时间】:2022-06-21 22:16:48
【问题描述】:

我有一个在我的应用程序中使用的记录类。记录有一个公共 const,我希望在构造记录本身的同时实例化它。

但是,当我检查代码时,在记录中看不到 const 变量。这里出了什么问题?

public record TenantsUpdateNotification(string Serial, IEnumerable<TenantObject> Tenants)
{
    public const string RequestType = "TENANT_UPDATE";
};

【问题讨论】:

  • 常量是声明类型的一部分,而不是实例的一部分。它们是隐式静态的。见docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
  • 不清楚你在这里问什么。 “实例化” const 是什么意思?你说它无处可寻,你怎么找它,什么代码不起作用?您是否尝试使用 TenantsUpdateNotification.RequestType 访问 const?
  • 你可能会想到“常量”和“变量”的组合。它不能既是它的又是它。并且某些常量只存在一次,因此它附加到类而不是类的实例。

标签: c#


【解决方案1】:

const 在这里创建一个static 字段。如果您希望它成为实例成员,则应使用readonly

public record TenantsUpdateNotification(string Serial, IEnumerable<TenantObject> Tenants)
{
    public readonly string RequestType = "TENANT_UPDATE";
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多