【问题标题】:C# BinaryReader working weirdC# BinaryReader 工作异常
【发布时间】:2017-08-23 02:14:08
【问题描述】:

当我调用ReadByte 时,会执行一个被覆盖的Read 方法。

代码在这里

public object Read(Stream s)
{
    Issues.Clear();

    if (AutoReset)
        Reset();

    using (var r = new BinaryReader(s, Encoder, true))
    {
        // check stream begin
        if (r.ReadByte() != StreamBegin) // this r.ReadByte() goto..
        {

我在这里打电话给ReadByte。这个BinaryReader 来自System.IO

接下来ReadByte() 方法转到这里

public override int Read(byte[] buffer, int offset, int count)
{
    ..... Something
}

此方法在自定义类中。

调用堆栈在这里:

那么..为什么会发生这种情况?为什么这段代码会这样?

【问题讨论】:

  • ReadByte() 显然是根据Read(byte[],int,int) 实现的。这对你来说真的是一个很大的惊喜吗?
  • 该覆盖在哪个类中? ReadByte() 在其代码中调用 Read(byte[], int, int) 是正常的,因为所有 ReadByte() 所做的都是读取下一个字节然后推进流。 ReadByte 实现它自己的 Read 代码版本并没有真正的优势....
  • @Jeff Mercado,Clasies ReadByte 是从“公共类 InstanceSerializer”“命名空间 EMx.Serialization”调用的,ReadByte 调用的 Read 方法在“公共类 MxStream”“命名空间 EMx.IO.MxData”上。和 "public class InstanceSerializer" 没有使用 "EMx.IO.MxData" 。我想知道这些独立的类是如何协同工作的?

标签: c# methods io stream


【解决方案1】:

ReadByte() 调用 Read() 并将位置移动到下一个。所以 Read() 方法在自定义类中被覆盖,所以 ReadByte() 去覆盖的 Read() 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多