代码之家  ›  专栏  ›  技术社区  ›  Robert Harvey

如何概括这些不同数据结构的使用?

  •  1
  • Robert Harvey  · 技术社区  · 15 年前

    我有一个从文件中读取时间的应用程序。根据文件中其他位置的标志位,这些时间可以采用三种不同的格式,如下所示:

    [StructLayout(LayoutKind.Sequential, Pack = 1]
    public struct IntraPacketTime_RTC
    {
        public UInt64 RTC;
    }
    
    [StructLayout(LayoutKind.Sequential, Pack = 1]
    public struct IntraPacketTime_Ch4
    {
        public UInt16 Unused;
        public UInt16 TimeHigh;
        public UInt16 TimeLow;
        public UInt16 MicroSeconds;
    }
    
    [StructLayout(LayoutKind.Sequential, Pack = 1]
    public struct IntraPacketTime_IEEE1588
    {
        public UInt32 NanoSeconds;
        public UInt32 Seconds;
    }
    

    如您所见,所有三种时间格式在源数据文件中都占8个字节,但这8个字节是 铸造不同 ,取决于指定的时间格式。

    但是,输出时间总是相同的格式,不管它存储在源数据文件中的方式如何(或者 年月日时分 ,其中ssssss是一秒钟的分数,或 SSSSS 以秒和小数秒表示)。

    如何从数据文件中读取这些时间并以常规方式使用它们,而不需要 case 到处都是声明?有没有一种软件模式可以简化这一过程,使其更通用化,并抽象出一些复杂性?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Mark H    15 年前
    [StructLayout(LayoutKind.Explicit)]
    public struct IntraPacketTime {
        [FieldOffset(0)]
        private UInt64 RTC;
    
        [FieldOffset(0)]
        private UInt32 NanoSeconds;
        [FieldOffset(4)]
        private UInt32 Seconds;
    
        [FieldOffset(0)]
        private UInt16 Unused;
        [FieldOffset(2)]
        private UInt16 TimeHigh;
        [FieldOffset(4)]
        private UInt16 TimeLow;
        [FieldOffset(6)]
        private UInt16 MicroSeconds;        
    
        public DateTime GetTime(IntraPacketTimeFormat format) {
            switch (format) {
                ...
            }
        }
        public explicit operator IntraPacketTime(Int64 value) {
            return new IntraPacketTime { RTC = value; }
        }
    }
    
    public enum IntraPacketTimeFormat {
        None,
        RTC,
        Ch4,
        IEEE1588,
    }
    

    你应该能用

    IntraPacketTime t = (IntraPacketTime)binaryReader.ReadInt64();
    var time = t.GetTime(IntraPacketTimeFormat.Ch4);
    
        2
  •  0
  •   David Gladfelter    15 年前

    我建议使用存储库模式。

    class TimeReader
    {
        public void ExtractTimeFormat(StreamReader data)
        {
            // read the flag and set state so that ExtractTime will return the
            // correct time implemenation
        }
        public ITime ExtractTime(StreamReader data)
        {
            // extract the appropriate time instance from the data based on
            // the current time format
        }
    }
    
    interface ITime
    {
        void WriteTime(StreamWriter data);  
        void WriteTimeFlags(StreamWriter data);
        DateTime GetTime();
    }
    

    唯一的case语句是在extractTime中,其余的代码可以对抽象进行操作。