简体   繁体   中英

Use generic class for generic parameter base with out generic parameter

Is it possible to do some thing like this in 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

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.

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. If U is a nullable reference type, T may be either nullable or non-nullable.

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

class Foo { }

class Foo<T> where T: Bar { }

class MyClass<TFoo> where TFoo : Foo { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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