繁体   English   中英

使用泛型 class 作为泛型参数基,没有泛型参数

[英]Use generic class for generic parameter base with out generic parameter

是否可以在 C# 中做这样的事情?

class Foo<T> where T : Bar{}
class MyClass<TFoo> where TFoo : Foo<> {}

我不想这样使用它。 实际上它有 5 个以上的通用参数

class Foo<T> where T : Bar{}
class MyClass<TFoo, T> where TFoo : Foo<T> {}

在查看官方文档时,我们可以看到语言规范指出:

where T: <base class name>

类型参数必须是或派生自指定基数 class。在 C# 8.0 及更高版本的可空上下文中,T 必须是从指定基数 class 派生的不可空引用类型。

例子:

public class Foo<T> where T: Bar
{
}

where T: U

为 T 提供的类型参数必须是或派生自为 U 提供的参数。在可为 null 的上下文中,如果 U 是不可为 null 的引用类型,则 T 必须是不可为 null 的引用类型。 如果 U 是可空引用类型,则 T 可以是可空或不可空的。

例子:

//Type parameter V is used as a type constraint.
public class SampleClass<T, U, V> where T : V { }

通常,你不能有像这样的通用声明语法:

public class Foo<T> where T: Bar<> // <> using this syntax is not allowed.

因此,在上述情况下,最适合您的版本可能是:

class Foo<T> where T: Bar{}
class MyClass<TFoo, T> where TFoo : Foo<T> {}

或者(正如@Jon 正确提到的那样):

class Foo { }

class Foo<T> where T: Bar { }

class MyClass<TFoo> where TFoo : Foo { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM