问题
What is the right way to add comments with C# 9 record with Nullable enabled?
If I try
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; }
}
I get warning.
Non-nullable property 'FirstName' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
If I try
public record Person(string firstName, string lastName);
I get warning.
Missing XML comment for publicly visible type or member 'Person.firstName'
This does not work either.
/// <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);
Gives warning.
XML comment has a param tag for 'FirstName', but there is no parameter by that name
回答1:
One way worth evaluating to avoid the warnings in this scenario would be to use the null-forgiving operator.
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!;
}
回答2:
For the first case, the warning you're getting is unrelated to documentation comments. You have a non-nullable property with default value equals to null
. That's why you get warning.
For the second case, this is a known issue in the compiler that's being fixed in dotnet/roslyn#49134.
来源:https://stackoverflow.com/questions/64613788/what-is-the-right-way-to-add-comments-with-c9-record