c# - 在静态类中定义的类的约束

标签 c# namespaces

您好,有什么方法可以限制在静态类中定义的类的泛型方法吗?

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?



不,没有。

唯一的类型约束是:
  • 需要公共(public)无参数构造函数 ( where T : new() )
  • 要求它是一个引用类型 ( where T : class )
  • 要求它是不可为空的值类型 ( where T : struct )
  • 需要将身份转换为特定类型或类型参数(where T : Button 或其他)

  • “包含在特定类型中”没有限制,我也不希望这是一个新功能 - 这听起来像是一个非常小众的用例。

    您可以创建一个只有这些类型实现的接口(interface),但这与我建议的差不多。 (如果它是在同一个包含类中声明的私有(private)接口(interface),则只有那些类可以实现它 - 但泛型方法也需要是私有(private)的。)

    关于c# - 在静态类中定义的类的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49571423/

    相关文章:

    c# - 使用 DataContractSerializer 反序列化对象中的 XML

    c# - 如何将 EF 与 SQLite 和 Visual Studio 2013 结合使用

    C# 使用 EWS 创建日历项,如何取回结果?

    c# bitarray 索引的正位

    c# - 将参数从 aspx 传递到 javascript 问题

    python - Doxygen python 链接到函数

    Javascript - 类路径可以有命名空间吗?

    c# - 有条件地选择命名空间进行实例化

    c++ - STL 中使用 operator== 的命名空间解析

    Python XML 解析