[英]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.