gpt4 book ai didi

c# - 如果 T 在泛型中为空怎么办?如何省略尖括号

转载 作者:太空狗 更新时间:2023-10-29 20:03:16 26 4
gpt4 key购买 nike

我有一个这样的类:

class A<TResult>
{
public TResult foo();
}

但有时我需要将此类作为非泛型类来使用,即类型TResultvoid
我无法通过以下方式实例化该类:

var a = new A<void>();

此外,我不想指定省略尖括号的类型:

var a = new A();

我不想重写整个类,因为它做同样的事情。

最佳答案

void不是 C# 中的真实类型,即使有相应的 System.Void FCL 中的结构。恐怕您在这里需要一个非通用版本:

class A
{
//non generic implementation
}

class A<T> : A
{
//generic implementation
}

可以看到FCL里面有System.Action/System.Action<T> , 而不是 System.Action<void> ,以及 Task而不是 Task<void> .

编辑 来自 CLI specification(ECMA-335) :

The following kinds of type cannot be used as arguments ininstantiations (of generic types or methods):

Byref types (e.g., System.Generic.Collection.List`1<string&> isinvalid)

Value types that contain fields that can point into the CIL evaluation stack (e.g.,List<System.RuntimeArgumentHandle>)

void (e.g.,List<System.Void> is invalid)

关于c# - 如果 T 在泛型中为空怎么办?如何省略尖括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13083272/

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