【问题标题】:Swapping two elements in a list covariantly协变交换列表中的两个元素
【发布时间】:2014-01-08 23:40:33
【问题描述】:

你可以为通用列表协变地编写一个交换例程吗?这是一个不起作用的交换例程:

public static void Swap(List<IComparable> list, int pos1, int pos2)
{
    IComparable temp = list[pos1];
    list[pos1] = list[pos2];
    list[pos2] = temp;
}

调用Swap(new List&lt;int&gt;{1,2}, 0, 1) 在这里不起作用,因为此版本的 Swap 不是协变的。

【问题讨论】:

  • 如果你添加一些示例代码,甚至是伪代码,就会更容易理解你在说什么。
  • 文字墙,没有代码。我懒得读这些了。
  • @HighCore 并非每个编程问题都与代码有关。习惯就好。
  • @DarrellPlank 请编辑您的问题,而不是将代码作为评论发布。

标签: c# list sorting generics covariance


【解决方案1】:

这对你有用吗?

public static void Swap<T>(this List<T> list, int pos1, int pos2)
{
    T tmp = list[pos1];
    list[pos1] = list[pos2];
    list[pos2] = tmp;

}

这允许您指定类型并使交换成为可能。

【讨论】:

  • 很好的答案,jsobo。笨到我都认不出来了。下次出现这种情况时会更好地准备!再次感谢!
猜你喜欢
  • 1970-01-01
  • 2020-11-23
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 2012-01-18
相关资源
最近更新 更多