C# generic type constraint for everything nullable

后端 未结 8 2100
无人共我
无人共我 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:57

    If you are willing to make a runtime check in Foo's constructor rather than having a compile-time check, you can check if the type is not a reference or nullable type, and throw an exception if that's the case.

    I realise that only having a runtime check may be unacceptable, but just in case:

    public class Foo
    {
        private T item;
    
        public Foo()
        {
            var type = typeof(T);
    
            if (Nullable.GetUnderlyingType(type) != null)
                return;
    
            if (type.IsClass)
                return;
    
            throw new InvalidOperationException("Type is not nullable or reference type.");
        }
    
        public bool IsNull()
        {
            return item == null;
        }
    }
    

    Then the following code compiles, but the last one (foo3) throws an exception in the constructor:

    var foo1 = new Foo();
    Console.WriteLine(foo1.IsNull());
    
    var foo2 = new Foo();
    Console.WriteLine(foo2.IsNull());
    
    var foo3= new Foo();  // THROWS
    Console.WriteLine(foo3.IsNull());
    

提交回复
热议问题