Implementing Nullable Types in Generic Interface

So in a previous question I asked about implementing a generic interface with a public class and bingo, it works. However, one of the types I'm looking to pass in is one of the built in nullable types such as: int, Guid, String, etc.

Here's my Interface:

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

So when I implement this like so:

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

    public MyCustomClass Get(Int32 testID)
    {
        throw new NotImplementedException();
    }
}

I receive the error message: The type 'int' must be a reference type in order to use it as parameter 'U' in the generic type or method 'TestApp.IOurTemplate'

I've tried to infer the type Int32?, but same error. Any ideas?


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

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

public class MyClass<T> where T : class 
{

}

Nullable types don't satisfy class or struct constraints:

C# Language Specification v3.0 (Section §10.1.5: Type parameter constraints):

The reference type constraint specifies that a type argument used for the type parameter must be a reference type. All class types, interface types, delegate types, array types, and type parameters known to be a reference type (as defined below) satisfy this constraint. The value type constraint specifies that a type argument used for the type parameter must be a non-nullable value type.

All non-nullable struct types, enum types, and type parameters having the value type constraint satisfy this constraint. Note that although classified as a value type, a nullable type (§4.1.10) does not satisfy the value type constraint. A type parameter having the value type constraint cannot also have the constructor-constraint.


Any reason why you need to restrict type U to class?

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();
    }
}

FYI: int? is the C# shorthand for Nullable<int> .

链接地址: http://www.djcxy.com/p/43720.html

上一篇: 在Eclipse IDE中跳转到接口实现

下一篇: 在通用接口中实现可空类型