Java中List和Iterator的c等价物是什么

本文关键字:等价物 是什么 Iterator List Java | 更新日期: 2023-09-27 18:22:00

我正在手动将此Java代码转换为C#:

private static final List<BigInteger> PRIMES = Arrays.asList(new BigInteger[]
    { new BigInteger("10007"), new BigInteger("10009"),
      new BigInteger("10037"), new BigInteger("10039")});
Iterator<BigInteger> primes = PRIMES.iterator();

这是我在C#中的代码:

private static readonly List<BigInteger> PRIMES = new List<BigInteger> {
    10007, 10009,
    10037, 10039 };
IEnumerable<BigInteger> primes = PRIMES.AsEnumerable<BigInteger>();

但是,我不确定我的代码是否正确。我真的不理解C#中的列表和迭代器。

请任何人帮助我正确转换代码,任何帮助都是非常重要的。

非常感谢。

Java中List和Iterator的c等价物是什么

您的代码是正确的。List<T>是java ArrayList<T>的C#等价物,而IEnumerable<T>或多或少是java Iterator<T>的等价物。公共API有点不同,但最终目标是相同的。

请注意,不需要AsEnumerable调用。由于List<T>实现了IEnumerable<T>,您只需编写:

IEnumerable<BigInteger> primes = PRIMES;

也就是说,调用AsEnumerable并没有什么错,也没有什么代价。

您的代码看起来不错,但请注意,c#中的List可以通过索引访问,因此根据您所做的操作,您可能不需要等效的迭代器。

Java的"List"是一个接口,因此.NET的等效项是"IList",而与Java的Iterator等效的.NET是"IEnumerator",而不是"IEnumerable":

private static readonly IList<System.Numerics.BigInteger> PRIMES = new System.Numerics.BigInteger[] { 10007, 10009, 10037, 10039 };
internal IEnumerator<System.Numerics.BigInteger> primes = PRIMES.GetEnumerator();