calling an overloaded method in generic method

后端 未结 5 1686
日久生厌
日久生厌 2021-01-12 23:18
class Test
{
    public BinaryWriter Content { get; private set; }
    public Test Write (T data)
    {
        Content.Write(data);
        return this;
           


        
5条回答
  •  死守一世寂寞
    2021-01-12 23:55

    1. Using Reflection considerably slows down method calls. It also moves argument type check from compile time to runtime, which is undesirable in most cases.

    2. Using dynamic calls in this case is just a fancy and slightly optimized version of the previous method which has the same drawbacks.

    3. The correct way is to copy all overloads:

      public Test Write (bool data)
      {
          Content.Write(data);
          return this;
      }
      
      public Test Write (byte data)
      {
          Content.Write(data);
          return this;
      }
      
      public Test Write (byte[] data)
      {
          Content.Write(data);
          return this;
      }
      
      public Test Write (char data)
      {
          Content.Write(data);
          return this;
      }
      
      public Test Write (char[] data)
      {
          Content.Write(data);
          return this;
      }
      
      // ...
      

      This method is very verbose, but it is the only that provides compile-time checks of arument types and is the most performant as it chooses overloads and compile-time. Furthermore, these methods are likely to be inlined.

      In cases like this, I usually use a T4 script which generates code like above based on Reflection. Create a TT file, enumerate Write overloads of BinaryWriter, generate code.

提交回复
热议问题