代码之家  ›  专栏  ›  技术社区  ›  Jason N. Gaylord

在泛型接口中实现可为空的类型

  •  9
  • Jason N. Gaylord  · 技术社区  · 15 年前

    所以在前面的一个问题中,我问过如何实现一个公共类和bingo的通用接口,它是有效的。但是,我要传递的类型之一是内置的可以为空的类型,例如:int、guid、string等。

    这是我的界面:

    public interface IOurTemplate<T, U>
        where T : class
        where U : class
    {
        IEnumerable<T> List();
        T Get(U id);
    }
    

    所以当我像这样实现这一点时:

    public class TestInterface : IOurTemplate<MyCustomClass, Int32>
    {
        public IEnumerable<MyCustomClass> List()
        {
            throw new NotImplementedException();
        }
    
        public MyCustomClass Get(Int32 testID)
        {
            throw new NotImplementedException();
        }
    }
    

    我收到错误消息: 类型“int”必须是引用类型才能用作泛型类型或方法“testapp.iourtemplate”中的参数“u”

    我试着推断出32的类型?,但同样的错误。有什么想法吗?

    3 回复  |  直到 8 年前
        1
  •  7
  •   johnnyRose    8 年前

    我不会真的这么做,但这可能是唯一让它工作的方法。

    public class MyWrapperClass<T> where T : struct 
    {
        public Nullable<T> Item { get; set; }   
    }
    
    public class MyClass<T> where T : class 
    {
    
    }
    
        2
  •  6
  •   Mehrdad Afshari    15 年前

    可为空的类型不满足 class struct 制约因素:

    C语言规范v3.0(第10.1.5节:类型参数约束):

    引用类型约束指定用于类型参数的类型参数必须是引用类型。已知为引用类型(定义如下)的所有类类型、接口类型、委托类型、数组类型和类型参数都满足此约束。 值类型约束指定用于类型参数的类型参数必须是不可为空的值类型。

    具有值类型约束的所有不可为空的结构类型、枚举类型和类型参数都满足此约束。 请注意,尽管被分类为值类型,但可以为空的类型(§4.1.10)不满足值类型约束。 具有值类型约束的类型参数也不能具有构造函数约束。

        3
  •  1
  •   johnnyRose    8 年前

    你为什么要把U型限制在课堂上?

    public interface IOurTemplate<T, U>
        where T : class
    {
        IEnumerable<T> List();
        T Get(U id);
    }
    
    public class TestInterface : IOurTemplate<MyCustomClass, Int32?>
    {
        public IEnumerable<MyCustomClass> List()
        {
            throw new NotImplementedException();
        }
    
        public MyCustomClass Get(Int32? testID)
        {
            throw new NotImplementedException();
        }
    }
    

    FY: int? C是 Nullable<int> .