【问题标题】:Change Code to .net 2.0将代码更改为 .net 2.0
【发布时间】:2011-04-22 21:16:38
【问题描述】:

.net 2.0 似乎不支持字典键的 OrderByDescending,如何将此代码更改为 .net 2.0

    private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>()
 {
     { new byte[]{ 0x42, 0x4D }, DecodeBitmap},
     { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },
     { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },
     { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },
     { new byte[]{ 0xff, 0xd8 }, DecodeJfif },
 };


public static Size GetDimensions(BinaryReader binaryReader)
     {
         int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;
         byte[] magicBytes = new byte[maxMagicBytesLength];
         for (int i = 0; i < maxMagicBytesLength; i += 1)
         {
             magicBytes[i] = binaryReader.ReadByte();
             foreach (var kvPair in imageFormatDecoders)
             {
                 if (magicBytes.StartsWith(kvPair.Key))
                 {
                     return kvPair.Value(binaryReader);
                 }
             }
         }
         throw new ArgumentException(errorMessage, "binaryReader");
     }

【问题讨论】:

  • 嗯? OrderByDescending 调用在 .NET 3.5 中应该没问题...但是您为什么希望迁移到 2.0 来解决问题?你认为byte[].StartsWith 来自哪里?
  • @oded - 听起来像是缺少使用 directive

标签: c# .net-3.5 .net-2.0


【解决方案1】:

这一行

int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;

只获取字典键中最长字节数组的长度。因此,只需遍历 imageFormatDecoders 中的项目并记录最长的值,即类似这样的内容(未经测试):

int maxMagicBytesLength = 0;
foreach (byte[] magicBytes in imageFormatDecoders.Keys) {
    if (magicBytes.Length > maxMagicBytesLength)
        maxMagicBytesLength = magicBytes.Length;
}

【讨论】:

  • 嗨,谢谢,你的方法是对的,但是我如何在 dot net 2.0 中处理 byte[].StartsWith 呢?
  • @Ata:将 foreach 循环移到 for 循环之外。在 foreach 循环中,创建一个比较第一个 kvPair.Key.Length 项的循环。
【解决方案2】:

我怀疑你只是缺少;

using System.Linq;

在代码文件的顶部。不,切换到 .net 2 在这里无济于事。

【讨论】:

    【解决方案3】:

    在 .Net 3.5 中有什么问题?

    Dictionary<int, int> dict = new Dictionary<int, int>();
    dict[0] = 2;
    dict[1] = 3;
    
    foreach (var item in dict.OrderByDescending(key => key.Value))
    {
        Console.WriteLine(item.Key);
        Console.WriteLine(item.Value);
    } 
    

    输出

    1

    3

    0

    2

    【讨论】:

      【解决方案4】:

      .net 3.5 不支持OrderByDescending 是什么意思。确实如此。顺便问一下Max(x =&gt; x.Length) 有什么问题?

      【讨论】:

      • 嗨,谢谢,你能解释一下你想用什么来做这个吗?
      • @Ata: int maxMagicBytesLength = imageFormatDecoders.Keys.Max(x =&gt; x.Length).
      • 你错了,dot net 2.0不允许我使用dot net 3.5组件。
      • WTF,您一开始说您使用的是 .net 3.5。我可以看到你现在改变了你的问题,但我必须承认我没有注意到这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多