Receiving error about nullable type parameter even when parameter has notnull constraint

前端 未结 3 481
既然无缘
既然无缘 2021-01-18 14:13

I have a generic interface IDataAdapter; implementors of the interface should be able to read POCOs with Guid IDs from a data source.

3条回答
  •  误落风尘
    2021-01-18 14:55

    If you look at Nullable Struct's documentation you can see that it requires to be a struct:

    public struct Nullable where T : struct
    

    I believe you will need to constraint T to be a struct:

    interface IA where T : struct
    {
        T? Read(Guid id);
        // Or Nullable Read(Guid id);
    }
    
    
    class A : IA
    {
        public int? Read(Guid id) { Console.WriteLine("A"); return 0; }
    }
    

    BTW. Could you give us an example of what types you want to use this class with?

    Why not just use where T: class and return T (or even not have a constraint at all)?

    interface IA where T : class
    {
        T Read(Guid id);
    }
    

提交回复
热议问题