【发布时间】:2018-11-07 19:07:54
【问题描述】:
我在 python 脚本中遇到了这种语法,发现它被称为切片赋值。您如何在 C# 中编写此语法?
self.nav[:] = []
【问题讨论】:
-
对于那些不会说python的人,这个赋值将
nav数组(或列表)的内容替换为右侧数组(或列表)的内容。所以nav[:] = []基本上清除了数组/列表。
我在 python 脚本中遇到了这种语法,发现它被称为切片赋值。您如何在 C# 中编写此语法?
self.nav[:] = []
【问题讨论】:
nav数组(或列表)的内容替换为右侧数组(或列表)的内容。所以nav[:] = [] 基本上清除了数组/列表。
C#没有切片赋值操作符,但是可以使用List<T>提供的方法来代替:
list[a:b] = otherList
等价于
list.RemoveRange(a,b-a);
list.InsertRange(a, otherList);
或者,在
的空间情况下list[:] = []
你可以写
list.Clear();
从技术上讲,您可以编写自己的列表类,它继承自 List<T> 并模拟 python 的行为(至少部分):
public class ExtendedList<T> : List<T>
{
public IEnumerable<T> this[int start, int end]
{
get
{
return this.Skip(start).Take(end - start);
}
set
{
int num = end - start;
RemoveRange(start, Count - num > 0 ? num : 0);
InsertRange(start, value);
}
}
}
【讨论】:
RemoveRange 方法采用起始索引和计数,而不是结束索引。
list[:] = []