繁体   English   中英

这些JAVA Collections方法的C#等效项

[英]C# equivalent for these JAVA Collections methods

嗨,我正在用C#重写Java代码,并且被困在这里:

public void printSolveInstructions() {
    System.out.print(getSolveInstructionsString());
}

public String getSolveInstructionsString() {
    if (isSolved()) {
        return historyToString(solveInstructions);
    } else {
        return "No solve instructions - Puzzle is not possible to solve.";
    }
}

public List<LogItem> getSolveInstructions() {
    if (isSolved()) {
        return Collections.unmodifiableList(solveInstructions);
    } else {
        return Collections.emptyList();
    }
}

我知道如何重写前两个方法(用于引用最后一个方法),但是我不知道Collections.unmodifiableList()Collections.emptyList() solveInstructions方法的solveInstructions类型为List这里是Java和C#中的声明:

private ArrayList<LogItem> solveInstructions = new ArrayList<LogItem>() // java
private List<LogItem> solveInstructions = new List<LogItem>() // c#

更新我以这种方式重写了getSolveInstructions()方法:

public List<LogItem> getSolveInstructions()
    {
        if (isSolved())
        {
            return solveInstructions.AsReadOnly();
        }
        else
        {
            return new List<LogItem>();
        }
    }

现在问题出在我使用.AsReadOnly()时,ide给了我一个错误

您的方法返回List<LogItem>IReadOnlyCollection<LogItem> (通过调用List<T>.AsReadOnly()方法产生;但是,您的返回类型为List<LogItem> ,它与IReadOnlyCollection<LogItem>不兼容) IReadOnlyCollection<LogItem> 。将方法返回类型更改为IList<LogItem> ,这两种类型均适用。

注意,由于此方法可以返回只读列表或读写列表,因此调用代码应在尝试修改返回的集合的IsReadOnly属性之前对其进行检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM