如何在 C# dotnet 中限制多个泛型参数
how does one restrict multiple generics arguments in C# dotnet
你如何 "restrict" 在 2 个或更多(多个)占位符上?
public abstract class MyBaseClass<T> : ISomethingElse<T> where T : struct
{
}
请注意,T 仅限于 "struct",这些年来我已经多次这样做了。
以上工作正常
现在我想创建一个通用的 class 定义,我想对 T 和 K 施加约束。
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K> where T : struct , K : struct
{
}
以上..我想不出神奇的语法糖。
我知道"easy"。
您需要 where
关键字两次。
class Foo<T, K>
where T : struct
where K : struct
{
}
这些是对类型参数的约束,documentation 有很多关于它们的有用信息。
您可以通过为由 space 分隔的每个参数包含一个 where
约束来限制多个通用参数。因此,在您的代码片段中,这将如下所示:
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K> where T : struct where K : struct
{
}
或者更易读的版本是:
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K>
where T : struct
where K : struct
{
}
你如何 "restrict" 在 2 个或更多(多个)占位符上?
public abstract class MyBaseClass<T> : ISomethingElse<T> where T : struct
{
}
请注意,T 仅限于 "struct",这些年来我已经多次这样做了。
以上工作正常
现在我想创建一个通用的 class 定义,我想对 T 和 K 施加约束。
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K> where T : struct , K : struct
{
}
以上..我想不出神奇的语法糖。
我知道"easy"。
您需要 where
关键字两次。
class Foo<T, K>
where T : struct
where K : struct
{
}
这些是对类型参数的约束,documentation 有很多关于它们的有用信息。
您可以通过为由 space 分隔的每个参数包含一个 where
约束来限制多个通用参数。因此,在您的代码片段中,这将如下所示:
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K> where T : struct where K : struct
{
}
或者更易读的版本是:
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K>
where T : struct
where K : struct
{
}