Calling an overloaded method in a generic method

class Test
{
    public BinaryWriter Content { get; private set; }
    public Test Write<T> (T data)
    {
        Content.Write(data);
        return this;
    }
}

it will not compile.

1. The best overloaded method match for 'System.IO.BinaryWriter.Write(bool)' has some invalid arguments
2. Argument 1: cannot convert from 'T' to 'bool'

it looks like Test.Write is always trying to call BinaryWriter.Write (bool). any suggestions?

+4
source share
5 answers

Overload resolution occurs during compilation, in which case nothing is known about T, so overloading is not applicable.

   class Test
    {
        public BinaryWriter Content { get; private set; }
        public Test Write<T>(T data)
        {
            Content.Write((dynamic)data);
            return this;
        }
    }

But of course, this can cause some problems. For example, the application will compile if you send a DateTime to a method. But, it will be an exception.

+4
source

In your method, writing Tis general, which means it Tcan be anything, but BinaryWriter.Writedoes not accept general overload. Therefore, you cannot do this.

+1
source

.

T , Write . , T (, Write(object)).

+1

, . Reflection Write T.

BinaryWriter Stream , Reflection, :

class Test
{
    public BinaryWriter Content { get; private set; }

    public Test(Stream stream)
    {
        Content = new BinaryWriter(stream);
    }

    public Test Write<T>(T data)
    {

        var method = typeof (BinaryWriter).GetMethod("Write", new[] {data.GetType()});
        if (method != null)
        {
            method.Invoke(Content, new object[] { data });
        }
        // here you might want to throw an exception if method is not found

        return this;
    }
}

:

Test writer;
using (var fs = new FileStream("sample.txt", FileMode.Open))
{
     writer = new Test(fs);
     writer = writer.Write(232323);
     writer = writer.Write(true);
     writer = writer.Write(12);
}

using (var fs = File.Open("sample.txt", FileMode.Open))
{
    var reader = new BinaryReader(fs);
    Console.WriteLine(reader.ReadInt32());  // 232323
    Console.WriteLine(reader.ReadBoolean()); // true
    Console.WriteLine(reader.ReadByte());    // 12
}
+1
  • Reflection . , .

  • - , .

  • - :

    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;
    }
    
    // ...
    

    , , arument , . , , , .

    T4 script, , , Reflection. TT, Write BinaryWriter, .

-1
source

Source: https://habr.com/ru/post/1531895/


All Articles