gpt4 book ai didi

一切可为空的 C# 泛型类型约束

转载 作者:IT王子 更新时间:2023-10-29 03:36:53 28 4
gpt4 key购买 nike

所以我有这个类:

public class Foo<T> where T : ???
{
private T item;

public bool IsNull()
{
return item == null;
}

}

现在我正在寻找一个类型约束,它允许我将所有内容用作可以为 null 的类型参数。这意味着所有引用类型,以及所有 Nullable (T?) 类型:

Foo<String> ... = ...
Foo<int?> ... = ...

应该是可以的。

使用 class 作为类型约束只允许我使用引用类型。

附加信息:我正在编写一个管道和过滤器应用程序,并希望使用一个 null 引用作为传递到管道中的最后一项,以便每个过滤器都可以很好地关闭、进行清理等...

最佳答案

如果您愿意在 Foo 的构造函数中进行运行时检查而不是编译时检查,您可以检查该类型是否不是引用或可空类型,如果是这种情况则抛出异常。

我意识到只进行运行时检查可能是 Not Acceptable ,但以防万一:

public class Foo<T>
{
private T item;

public Foo()
{
var type = typeof(T);

if (Nullable.GetUnderlyingType(type) != null)
return;

if (type.IsClass)
return;

throw new InvalidOperationException("Type is not nullable or reference type.");
}

public bool IsNull()
{
return item == null;
}
}

然后下面的代码编译通过,但是最后一个(foo3)在构造函数中抛出一个异常:

var foo1 = new Foo<int?>();
Console.WriteLine(foo1.IsNull());

var foo2 = new Foo<string>();
Console.WriteLine(foo2.IsNull());

var foo3= new Foo<int>(); // THROWS
Console.WriteLine(foo3.IsNull());

关于一切可为空的 C# 泛型类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19831157/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com