简体   繁体   English

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

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

Is it possible to do some thing like this in C#?是否可以在 C# 中做这样的事情?

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

I don't want to use it like this.我不想这样使用它。 in real thing it get 5+ generic parameter实际上它有 5 个以上的通用参数

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

When looking at the official documentation , we can see that the languages specification states:在查看官方文档时,我们可以看到语言规范指出:

where T: <base class name>

The type argument must be or derive from the specified base class. In a nullable context in C# 8.0 and later, T must be a non-nullable reference type derived from the specified base class.类型参数必须是或派生自指定基数 class。在 C# 8.0 及更高版本的可空上下文中,T 必须是从指定基数 class 派生的不可空引用类型。

Example:例子:

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

and

where T: U

The type argument supplied for T must be or derive from the argument supplied for U. In a nullable context, if U is a non-nullable reference type, T must be non-nullable reference type.为 T 提供的类型参数必须是或派生自为 U 提供的参数。在可为 null 的上下文中,如果 U 是不可为 null 的引用类型,则 T 必须是不可为 null 的引用类型。 If U is a nullable reference type, T may be either nullable or non-nullable.如果 U 是可空引用类型,则 T 可以是可空或不可空的。

Example:例子:

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

And generally, you can't have a generic declaration syntax like this:通常,你不能有像这样的通用声明语法:

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

So, the best version for you in the above case could be either:因此,在上述情况下,最适合您的版本可能是:

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

or (as correctly mentioned by @Jon):或者(正如@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