简体   繁体   中英

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?

I wouldn't really do this but it's probably the only way to get it to work.

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM