c# - 如何在单个类中混合可空 T 和不可空 T

标签 c# .net generics

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

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

我本来以为可以把T定义成notnull然后用T?使用我希望可为空的任何属性,同时我可以定义类/函数,尝试调用代码无法编译。

    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);

如果我在类中通过 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); 有效。

关于c# - 如何在单个类中混合可空 T 和不可空 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72489106/

相关文章:

c# - 泛型方法中的 InvalidCastException

java - 为给定的大小为 n 的集合查找大小为 k 的子集

java - Java 中的语法 <T extends Class<T>>

c# - 通过名称中止线程

.net - 是否可以将 .NET System.Diagnostics.Process 对象附加到正在运行的进程?

c# - 参数化查询的糟糕 Dapper 性能

C# SQL To Linq - 具有多个变量的Where 子句比较 (var1+var2) !=(var1+var2)

c# - SQL Server 中存储过程中的许多插入

c# - C# 中 0 - 1000 之间的随机数生成器

.net - 为什么我的小型 .NET 开发公司要从 Team Foundation Server 2008 升级到 2010?