Comparing a generic against null that could be a value or reference type?

前端 未结 2 1070
我寻月下人不归
我寻月下人不归 2020-12-24 01:11
public void DoFoo(T foo) where T : ISomeInterface
{
    //possible compare of value type with \'null\'.
    if (foo == null) throw new ArgumentNull         


        
2条回答
  •  忘掉有多难
    2020-12-24 02:02

    No, there won't be any problems, but if you want the warning to disappear, you can use the following:

    public void DoFoo(T foo) where T : ISomeInterface
    {
        if (ReferenceEquals(foo, null)) throw new ArgumentNullException("foo");
    }
    

    Alternatively you can do something like this:

    // when calling this with an actual T parameter, you have to either specify the type
    // explicitly or cast the parameter to T?.
    public void DoFoo(T? foo) where T : struct, ISomeInterface
    {
        if (foo == null)
        {
            // throw...
        }
    
        DoFooInternal(foo.Value);
    }
    
    public void DoFoo(T foo) where T : class, ISomeInterface
    {
        if (foo == null)
        {
            // throw...
        }
    
        DoFooInternal(foo); 
    }
    
    private void DoFooInternal(T foo) where T : ISomeInterface
    {
        // actual implementation
    }
    

提交回复
热议问题