首页 文章

在通用接口中实现可空类型

提问于
浏览
9

因此,在上一个问题中,我询问了如何使用公共类和宾果实现通用接口,它可以工作 . 但是,我想要传入的其中一种类型是内置的可空类型之一,例如: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'必须是引用类型,以便在泛型类型或方法中使用它作为参数'U' 'TestApp.IOurTemplate'

我试图推断类型Int32?,但同样的错误 . 有任何想法吗?

3 回答

  • 7

    我不会真的这样做,但它可能是让它发挥作用的唯一方法 .

    public class MyWrapperClass<T> where T : struct 
    {
        public Nullable<T> Item { get; set; }   
    }
    
    public class MyClass<T> where T : class 
    {
    
    }
    
  • 1

    可空类型不满足 classstruct 约束:

    C#语言规范v3.0(第10.1.5节:类型参数约束):引用类型约束指定用于type参数的类型参数必须是引用类型 . 已知为引用类型(如下定义)的所有类类型,接口类型,委托类型,数组类型和类型参数都满足此约束 . 值类型约束指定用于type参数的类型参数必须是非可空值类型 . 具有值类型约束的所有非可空结构类型,枚举类型和类型参数都满足此约束 . 请注意,虽然归类为值类型,但可空类型(第4.1.10节)不满足值类型约束 . 具有值类型约束的类型参数也不能具有构造函数约束 .

  • 6

    您需要将类型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();
        }
    }
    

    仅供参考: int?Nullable<int> 的C#简写 .

相关问题