10

因此,在上一个问题中,我询问了有关使用公共类和宾果游戏实现通用接口的问题,它可以工作。但是,我希望传入的类型之一是内置的可为空类型之一,例如: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”

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

4

3 回答 3

7

可空类型不满足class或不struct约束:

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

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

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

于 2009-08-28T03:35:26.763 回答
7

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

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

public class MyClass<T> where T : class 
{

}
于 2009-08-28T03:40:37.970 回答
1

有什么理由需要将 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>.

于 2009-08-28T04:56:19.393 回答