[英]how does one restrict multiple generics arguments in C# dotnet
How do you "restrict" on 2 or more (multiple) placeholders?您如何“限制”2 个或更多(多个)占位符?
public abstract class MyBaseClass<T> : ISomethingElse<T> where T : struct
{
}
Note, T is confined to a "struct", and I've done this several times over the years.请注意,T 仅限于“结构”,这些年来我已经多次这样做了。
the above works fine以上工作正常
Now I want to create a generic class definition, and I want to put a constraint on T AND K.现在我想创建一个通用类定义,我想对 T AND K 施加约束。
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K> where T : struct , K : struct
{
}
the above .. i cannot figure out the magic syntax sugar.以上..我无法弄清楚神奇的语法糖。
I know "easy".我知道“容易”。
You need the where
keyword twice.您需要两次
where
关键字。
class Foo<T, K>
where T : struct
where K : struct
{
}
Those are constraints on type parameters, and the documentation has a lot of useful information on them.这些是对类型参数的约束, 文档中有很多关于它们的有用信息。
You can restrict multiple generic arguments by including a where
constraint for each argument separated by a space.您可以通过为由空格分隔的每个参数包含
where
约束来限制多个通用参数。 So in your code snippet this would look like the following:因此,在您的代码片段中,这将如下所示:
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K> where T : struct where K : struct
{
}
or a more readable version would be:或者更易读的版本是:
public abstract class MyBaseClass<T, K> : ISomethingElse<T, K>
where T : struct
where K : struct
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.