简体   繁体   中英

C# equivalent for these JAVA Collections methods

hi I'm rewriting a java code in C# and I'm stuck here:

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();
    }
}

I know how to rewrite the first two methods (it's for referencing the last one) but I don't know the equivalent for Collections.unmodifiableList() and Collections.emptyList() solveInstructions is of type List here's the declaration in java and C#:

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

update I rewrote the getSolveInstructions() method in this way:

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

Now the problem is ide gives me an error when I use .AsReadOnly()

Your method returns either a List<LogItem> , or an IReadOnlyCollection<LogItem> (produced by call to List<T>.AsReadOnly() method; however, your return type is List<LogItem> , which is incompatible with the IReadOnlyCollection<LogItem> . Change your method return type to IList<LogItem> , which works for both types.

Note, since this method can return either a read-only or a read-write list, calling code should check the returned collection's IsReadOnly property, before attempting to modify it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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