C# generic type constraint for everything nullable

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

        public class Foo
        {
            private T item;
    
            public Foo(T item)
            {
                this.item = item;
            }
    
            public bool IsNull()
            {
                return object.Equals(item, null);
            }
        }
    
        var fooStruct = new Foo(3);
            var b = fooStruct.IsNull();
    
            var fooStruct1 = new Foo(3);
            b = fooStruct1.IsNull();
    
            var fooStruct2 = new Foo(null);
            b = fooStruct2.IsNull();
    
            var fooStruct3 = new Foo("qqq");
            b = fooStruct3.IsNull();
    
            var fooStruct4 = new Foo(null);
            b = fooStruct4.IsNull();
    

提交回复
热议问题