如何在单个 class 中混合可空 T 和不可空 T

How can I mix nullable and not nullable T within a single class

我正在使用 C# 10 和 VS2022,如果这会影响答案。

我正在尝试编写一个 class 来包含具有各种约束的参数。基本类型不应为空,一些参数(如默认值)也应如此,而其他一些参数需要为空(我将根据需要检查它们是否为空)。我找不到在 class.

中以任何方式混合类型的方法

我本来以为可以把T定义成notnull然后用T?使用任何我想要可为空的属性,同时我可以定义 class/functions 尝试调用代码无法编译的方式。

    public class Parameter<T> where T : notnull {
        public T Value { get; set;}
        public T? Min { get; set; }

        public void Set(T? value_) 
        {
        }
    }

Parameter<int> parameter = new();
parameter.Set(null);

如果我在 class 中通过 VS2022 检查 Set,它会正确显示 Set(T?value_) 作为参数,但如果我检查 parameter.Set,它会显示 Set(int value),并且然后拒绝编译上述用法:

Argument 1: cannot convert from int? to int

我考虑过将可空属性定义为 T2 并允许它为空,但我遇到了无法比较或分配 T 和 T2 的问题,这会破坏目的。

我是不是遗漏了一些愚蠢的东西,还是有其他方法可以做到这一点?

由于您在评论中表示:

All of my usage (as implied above) will be value types (int, float, bool primarily)

只需使用 struct generic constraint:

where T : struct - The type argument must be a non-nullable value type. For information about nullable value types, see Nullable value types. Because all value types have an accessible parameterless constructor, the struct constraint implies the new() constraint and can't be combined with the new() constraint. You can't combine the struct constraint with the unmanaged constraint.

public class Parameter<T> where T : struct {
    public T Value { get; set;}
    public T? Min { get; set; }

    public void Set(T? value_) 
    {
    }
}

这将允许 T? 解析为 nullable value type,这将使 parameter.Set(null); 有效。