void in C# generics?

后端 未结 7 1982
小蘑菇
小蘑菇 2020-12-13 03:11

I have a generic method that takes a request and provides a response.

public Tres DoSomething(Tres response, Treq request)
{/*stuff*/}


        
相关标签:
7条回答
  • 2020-12-13 03:49

    You could simply use Object as others have suggested. Or Int32 which I have seen some use. Using Int32 introduces a "dummy" number (use 0), but at least you can't put any big and exotic object into an Int32 reference (structs are sealed).

    You could also write you own "void" type:

    public sealed class MyVoid
    {
      MyVoid()
      {
        throw new InvalidOperationException("Don't instantiate MyVoid.");
      }
    }
    

    MyVoid references are allowed (it's not a static class) but can only be null. The instance constructor is private (and if someone tries to call this private constructor through reflection, an exception will be thrown at them).


    Since value tuples were introduced (2017, .NET 4.7), it is maybe natural to use the struct ValueTuple (the 0-tuple, the non-generic variant) instead of such a MyVoid. Its instance has a ToString() that returns "()", so it looks like a zero-tuple. As of the current version of C#, you cannot use the tokens () in code to get an instance. You can use default(ValueTuple) or just default (when the type can be inferred from the context) instead.

    0 讨论(0)
提交回复
热议问题