非可空类型的通用 throw 函数

Generic throw function for non-nullable types

我正在尝试使用 non-nullable properties during initialization.

将现有项目转换为使用 可空引用类型 属性

我正在使用这种方法来获取应该存在的属性:

public class Dog
{
    private Person? _person;
    public int Id { get; set; }

    public string Name { get; set; }

    public Person Person
    {
        get => _person ?? throw new InvalidOperationException(
            $"Unset property {nameof(_person)}. You probably forgot to Include it");
        set => _person = value;
    }
}

但是几乎每个 属性 都写这个很乏味,所以我尝试制作一个通用的 ThrowOrGet() 函数:

public static class Util
{
    public static T ThrowOrGet<T>([AllowNull] T obj)
    {
        if (obj == null)
        {
            throw new InvalidOperationException(
                $"Unset property {nameof(obj)}. You probably forgot to Include it");
        }
        return obj;
    }
}

这样使用的:

public class Dog
{
    private Person? _person;
    public int Id { get; set; }

    public string Name { get; set; }

    public Person Person
    {
        get =>  Util.ThrowOrGet(_person); ---> "Possible null reference return"
        set => _person = value;
    }
}

但是函数 Util.ThrowOrGet(_person); 现在说它是一个可能的 null 引用 return。如果我内联函数,它会按预期工作。 有没有办法制作一个通用函数来执行此操作?

如果你只打算在引用类型上使用 ThrowOrGet(你应该这样做,因为它对值类型没有意义),那么你应该这样声明它:

public static T ThrowOrGet<T>(T? obj) where T : class
{
    if (obj == null)
    {
        throw new InvalidOperationException(
            $"Unset property {nameof(obj)}. You probably forgot to Include it");
    }
    return obj;
}

这表示该函数接受一个可为 null 的参数,并且始终 returns 一个不可为 null 的引用。遵循这种模式比依赖属性更好,因为它们实际上只适用于复杂的情况,而这不是。