简体   繁体   English

为什么我收到警告说必须初始化一个不可为空的字段(当我确定我正在初始化它时)?

[英]Why am I getting warning that a non-nullable field must be initialised (When I'm sure I'm initialising it)?

I have:我有:

public abstract class Craft
{
    public Craft()
    {
        CurrentQuadrant = new Point(0, 0);
    }

    private Point _currentQuadrant;
    public Point CurrentQuadrant
    {
        get => _currentQuadrant;
        set
        {
            _currentQuadrant = value;
        }
    }
}

(Point is a simple xy pair). (点是一个简单的 xy 对)。

Why would that be giving me the warning that Non-nullable field '_currentQuadrant' must contain a non-null value when exiting the constructor ?为什么会Non-nullable field '_currentQuadrant' must contain a non-null value when exiting the constructor Doesn't the assignment make sure it's non-null?分配不是确保它是非空的吗?

Too little reputation to comment, so I'll post it here.名声太小,无法评论,所以我会在这里发布。

If you're using .NET 5+, you can use the [MemberNotNull] attribute (more info here ).如果您使用的是 .NET 5+,则可以使用[MemberNotNull]属性(更多信息在这里)。

Just put [MemberNotNull(nameof(_currentQuadrant)] on your constructor and the warning will disappear.只需将[MemberNotNull(nameof(_currentQuadrant)]放在您的构造函数上,警告就会消失。

Or you could just assign the value to _currentQuadrant instead of CurrentQuadrant .或者您可以将值分配给_currentQuadrant而不是CurrentQuadrant

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我会收到这些奇怪的 C# 8 “可空引用类型”警告:在退出构造函数之前,不可空字段必须包含非空值。? - Why am I getting these strange C# 8 “nullable reference types” warnings: Non-nullable field must contain a non-null value before exiting constructor.? 为什么在这里出现“因为它是非空值类型,所以无法将null转换为'ScheduleType'”? - Why am I getting “Cannot convert null to 'ScheduleType' because it is a non-nullable value type” here? 不知道为什么我得到“非静态字段需要对象引用” - Not sure why I'm getting “An object reference is required for the non-static field” 我收到一个stackoverflowexception,我不确定为什么 - I'm getting a stackoverflowexception and i'm not sure why 为什么我得到 null 条目,用于方法“ActionResult DisplaySearchResults() - Why am I am getting null entry for parameter 'CarLotID' of non-nullable type 'System.Int32' for method 'ActionResult DisplaySearchResults() 如果我使用非可空引用类型,如何显示我没有找到任何内容? - If I'm using non-nullable reference types, how do I show that I didn't find anything? 为什么会收到“非空成员的空值”错误? - Why am I receiving a “Null value for non-nullable member” error? 将不可为空的类型与 null 进行比较时出现错误 - I got an error when comparing non-nullable type to null 当我尝试映射实体(实体框架)的属性时,出现错误,类型“ __”必须是非空值类型 - When I try to map the properties for an entity (Entity Framework), I get the error the type '__' must be a non-nullable value type 获取“索引超出数组范围”异常,我不确定为什么 - Getting “Index was outside the bounds of the array” exception and I'm not sure why
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM