如何解决用C#9记录添加注释的正确方法是什么?
使用启用了Nullable的C#9记录添加注释的正确方法是什么?
如果我尝试
public record Person
{
/// <summary>
/// Gets the first name.
/// </summary>
public string FirstName { get; init; }
/// <summary>
/// Gets the last name.
/// </summary>
public string LastName { get; init; }
}
我得到警告。
Non-nullable property 'FirstName' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
如果我尝试
public record Person(string firstName,string lastName);
我得到警告。
Missing XML comment for publicly visible type or member 'Person.firstName'
这也不起作用。
/// <summary>
/// Person.
/// </summary>
/// <param name="FirstName">Get the first name.</param>
/// <param name="LastName">Get the last name.</param>
public record Person(string FirstName,string LastName);
发出警告。
XML comment has a param tag for 'FirstName',but there is no parameter by that name
解决方法
对于第一种情况,您得到的警告与文档注释无关。您有一个不可为空的属性,其默认值等于null
。这就是为什么您会收到警告。
对于第二种情况,这是dotnet/roslyn#49134中已解决的编译器中的已知问题。
,在这种情况下,值得评估的一种避免警告的方法是使用null-forgiving运算符。
public record Person
{
/// <summary>
/// Gets the first name.
/// </summary>
public string FirstName { get; init; } = null!;
/// <summary>
/// Gets the last name.
/// </summary>
public string LastName { get; init; } = null!;
}
,
你可以这样写:
public record Person(string FirstName,string LastName)
{
/// <summary>
/// Gets the first name.
/// </summary>
public string FirstName { get; init; } = FirstName;
/// <summary>
/// Gets the last name.
/// </summary>
public string LastName { get; init; } = LastName;
}
这样记录是用 (string,string)-constructor 和 deconstructor 创建的,就像这个符号的情况一样:
public record Person(string firstName,string lastName);
但你也有发表评论的属性。
BTW 据我所知,这是合法的,只要属性和参数具有相同的名称和相同的类型,编译器就知道该怎么做。
如果属性应具有不同的界面,例如 set
而不是 init
或仅 get
等,您也可以使用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。