[英]C# equivalent for these JAVA Collections methods
hi I'm rewriting a java code in C# and I'm stuck here: 嗨,我正在用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();
}
}
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#: 我知道如何重写前两个方法(用于引用最后一个方法),但是我不知道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#
update I rewrote the getSolveInstructions()
method in this way: 更新我以这种方式重写了getSolveInstructions()
方法:
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()
现在问题出在我使用.AsReadOnly()
时,ide给了我一个错误
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. 您的方法返回List<LogItem>
或IReadOnlyCollection<LogItem>
(通过调用List<T>.AsReadOnly()
方法产生;但是,您的返回类型为List<LogItem>
,它与IReadOnlyCollection<LogItem>
不兼容) IReadOnlyCollection<LogItem>
。将方法返回类型更改为IList<LogItem>
,这两种类型均适用。
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. 注意,由于此方法可以返回只读列表或读写列表,因此调用代码应在尝试修改返回的集合的IsReadOnly
属性之前对其进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.