使用 getter 和 setter 时可能出现空引用警告

问题描述 投票:0回答:1

我很困惑为什么当我的 setter 分配给可为 null 的值并且 getter 返回非 null 值时,我会收到 Null Reference 警告。

这是我的对象的代码:

public class LocationSensor
{
    private string? _contextualUnits;
    public string? UniqueUnits { get; set; }
    public string GeneralUnits { get; set; }
    /// <summary>
    /// This field is meant to embody the units based on the user viewing them. If this sensor
    /// has a unique unit, that is always taken. If not, we check to see if the application has
    /// specified a contextual unit based on the users chosen measurement system. If that is not specified,
    /// we default to the general units (usually the metric system).
    /// </summary>
    public string ContextualUnits
    {
        get { return UniqueUnits ?? _contextualUnits ?? GeneralUnits; }
        set { _contextualUnits = value; }
    }
    public string? ImperialUnits { get; set; }
}

这是我为

_contextualUnits
赋值的代码。

public async Task<LocationSensor> GetLocationSensorAsync(int sensorId, int locationId, bool? inMetric = null)
{
    LocationSensor locationSensor = await _locationSensorRepository.GetLocationSensorAsync(sensorId, locationId);
    if (inMetric != null)
    {
        locationSensor.ContextualUnits = inMetric.Value ? locationSensor.GeneralUnits : locationSensor.ImperialUnits;
    }
    return locationSensor;
}

鉴于我正在为可为空的私有字段分配一个可能为空的值,为什么我会在这一行收到“可能为空引用分配”警告

ls.ContextualUnits = inMetric.Value ? ls.GeneralUnits : ls.ImperialUnits;

c#
1个回答
0
投票

让我们看一下代码的更简化版本:

public class Program
{
    public static void Main()
    {
        string? newValue = null;
        MyClass c = new MyClass();
        c.MyProperty = newValue;
    }
}

public class MyClass
{
    private string? _backingField;
    public string MyProperty 
    {
        get => _backingField ?? "default";
        set => _backingField = value;
    }   
}

= newValue;
有相同的警告:“可能的空引用分配”。

您已指示编译器(因为您启用了可为空引用类型功能)

MyProperty
属性不应接受空值。这正是它通知您空赋值 (
= newValue;
) 违背您意愿的原因。

事实上,在底层,属性获取和设置为可为空的字符串并不重要。公共合同规定该财产不应接受 null。如何实施与实现这一愿望无关。

© www.soinside.com 2019 - 2024. All rights reserved.