【问题标题】:Passing both List and Array as argument of IEnumerable将 List 和 Array 作为 IEnumerable 的参数传递
【发布时间】:2012-11-08 20:57:56
【问题描述】:

我想创建一个可以同时接受 List<byte> 和字节数组作为参数的方法(正如 Resharper 建议的那样):

public static UInt16 GetSourceAddress(IEnumerable<byte> packet)
{
    return BitConverter.ToUInt16(new[] {packet[4], packet[5]}, 0);
}

但是我得到以下编译错误:

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<byte>'

我知道我可以继续使用 List 和 byte[] 进行两个重载,但是这个问题说明了什么?如何解决?

【问题讨论】:

    标签: c# .net generics resharper ienumerable


    【解决方案1】:

    如果您想要随机访问,请改用IList&lt;T&gt;

    public static UInt16 GetSourceAddress(IList<byte> packet)
    

    List&lt;byte&gt;byte[] 都实现了IList&lt;byte&gt;,并且它有一个索引器。

    【讨论】:

    • 感谢乔恩,部分可行,但我通过另一种方法得到了这个:cannot convert from 'System.Collections.Generic.IList&lt;byte&gt;' to 'System.Collections.Generic.List&lt;byte&gt;
    • @Saeid87:不,你不能这样做——但你显示的代码中没有任何内容需要 List&lt;byte&gt;。不知道你想做什么,很难给你建议。
    • 谢谢,我想通了,也必须将其他方法签名更改为 IList。
    【解决方案2】:

    试试这个

    public static UInt16 GetSourceAddress(IEnumerable<byte> packet){  
    
     return BitConverter.ToUInt16(new[] {packet.ElementAt(4), packet.ElementAt(5)}, 0);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-05
      • 2023-04-05
      • 2012-01-25
      • 2013-04-09
      • 1970-01-01
      • 2014-03-10
      • 2015-08-06
      • 1970-01-01
      相关资源
      最近更新 更多