C# generic type constraint for everything nullable

后端 未结 8 2114
无人共我
无人共我 2020-12-09 14:11

So I have this class:

public class Foo where T : ???
{
    private T item;

    public bool IsNull()
    {
        return item == null;
    }

}
         


        
8条回答
  •  余生分开走
    2020-12-09 14:55

    If you only want to allow nullable value types and reference types, and disallow non-nullable value types, then I think you're out of luck as of C# 9.

    I am writing a pipes and filters application, and want to use a null reference as the last item that passes into the pipeline, so that every filter can shut down nicely, do cleanup, etc...

    In other words, you need to reserve a special value that indicates the end-of-stream.

    Consider creating a wrapper type that provides this. It'd be similar to how Nullable is implemented, and has the additional benefit of allowing a non-end-of-stream null value to be transmitted, should that be useful.

    public readonly struct StreamValue
    {
        public bool IsEndOfStream { get; }
        public T Value { get; }
    }
    

提交回复
热议问题