OStack程序员社区-中国程序员成长平台

标题: c# - 为什么我不能使用 System.ValueType 作为泛型约束? [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-20 17:47
标题: c# - 为什么我不能使用 System.ValueType 作为泛型约束?

  • 为什么我不能使用约束where T : System.ValueType ?
  • 为什么 Microsoft 阻止这种类型
    从成为约束?


  • 示例:

    为什么我不能执行以下操作?
    // Defined in a .Net class
    public void bar<T>(T a) where T : ValueType {...}
    
    // Defined in my class
    public void foo<T>(T a) where T : ValueType 
    { bar<T>(a); }
    

    在 ValueType 上使用 struct 有什么区别?
    // Defined in my class
    public void foo<T>(T a) where T : struct 
    { bar<T>(a); }
    



    Best Answer-推荐答案


    使用有两个区别

    where T : struct
    


    where T : ValueType
    
  • 后者将允许 T成为 ValueType本身,这是一个引用类型。
  • 后者也允许 T为可空值类型

  • 这些差异中的第一个几乎永远不是您想要的。第二种可能偶尔有用; Nullable<T>有点奇怪,因为它既不满足 where T : struct也不是 where T : class约束。

    更有用的是约束
    where T : struct, System.Enum
    

    这是 C# 禁止的,我可以说没有充分的理由。见 my blog postUnconstrained Melody project有关更多信息。

    关于c# - 为什么我不能使用 System.ValueType 作为泛型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1854625/






    欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4