您好,有什么方法可以限制在静态类中定义的类的泛型方法吗?
static class Container {
class A {
}
class B {
}
}
static class ContainerExtension
{
//(where T is a class defined in class Container)
public int[] ToArray<T>(T array) {
}
}
最佳答案
Is there any way to constrain a generic method for classes which are defined inside a static class?
不,没有。
唯一的类型约束是:
where T : new()
) where T : class
) where T : struct
) where T : Button
或其他)“包含在特定类型中”没有限制,我也不希望这是一个新功能 - 这听起来像是一个非常小众的用例。
您可以创建一个只有这些类型实现的接口(interface),但这与我建议的差不多。 (如果它是在同一个包含类中声明的私有(private)接口(interface),则只有那些类可以实现它 - 但泛型方法也需要是私有(private)的。)
关于c# - 在静态类中定义的类的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49571423/