[英]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.