我以为我的代码工作正常,但现在似乎没有。这就是我所拥有的:
public class NoteDetail
{
public NoteDetail()
{
_noteDetails = new List<string>();
}
public IList<string> NoteDetails { get { return _noteDetails; } }
private readonly List<string> _noteDetails;
}
我填写了这样的详细信息:
var noteDetail = new NoteDetail ();
noteDetail.NoteDetails.Add("aaa");
noteDetail.NoteDetails.Add("bbb");
noteDetail.NoteDetails.Add("ccc");
现在我想要洗牌所以我使用了这个例程:
public static void ShuffleGenericList<T>(IList<T> list)
{
//generate a Random instance
var rnd = new Random();
//get the count of items in the list
var i = list.Count();
//do we have a reference type or a value type
T val = default(T);
//we will loop through the list backwards
while (i >= 1)
{
//decrement our counter
i--;
//grab the next random item from the list
var nextIndex = rnd.Next(i, list.Count());
val = list[nextIndex];
//start swapping values
list[nextIndex] = list[i];
list[i] = val;
}
}
我的问题是我不知道怎么做洗牌。我试过以下但它给出了:
错误237参数1:无法从'System.Collections.Generic.IList'转换为'System.Collections.Generic.IList&lt; .Storage.Models.NoteDetail&gt;'
Sort.ShuffleGenericList<NoteDetail>(noteDetail.NoteDetails);
任何人都可以看到我做错了什么。这一切看起来都没关系,我不明白为什么我应该得到这个错误: - (
答案 0 :(得分:2)
你应该改变这个:
Sort.ShuffleGenericList<NoteDetail>(noteDetail.NoteDetails);
要:
Sort.ShuffleGenericList<string>(noteDetail.NoteDetails);
因为noteDetail.NoteDetails
是List<string>
,而不是List<NoteDetail>
。
答案 1 :(得分:0)
您使用了错误的类型来参数化您的泛型方法,请改为:
Sort.ShuffleGenericList(noteDetail.NoteDetails);
或更明确(但不必要):
Sort.ShuffleGenericList<string>(noteDetail.NoteDetails);
您传递NoteDetail
作为类型,而不是string
- 这将无效。
答案 2 :(得分:0)
我把你的代码扔进了VS.下面的一些小修改就可以了:
using System;
using System.Collections.Generic;
using System.Linq;
namespace MsgBaseSerializeationTest
{
class StackOverflow
{
public void Test()
{
var noteDetail = new NoteDetail<string>();
noteDetail.NoteDetails.Add("aaa");
noteDetail.NoteDetails.Add("bbb");
noteDetail.NoteDetails.Add("ccc");
NoteDetail<string>.ShuffleGenericList(noteDetail);
}
}
public class NoteDetail<T> : List<T>
{
public NoteDetail()
{
_noteDetails = new List<string>();
}
public IList<string> NoteDetails { get { return _noteDetails; } }
private readonly List<string> _noteDetails;
public static void ShuffleGenericList(IList<T> list)
{
//generate a Random instance
var rnd = new Random();
//get the count of items in the list
var i = list.Count();
//do we have a reference type or a value type
T val = default(T);
//we will loop through the list backwards
while (i >= 1) {
//decrement our counter
i--;
//grab the next random item from the list
var nextIndex = rnd.Next(i, list.Count());
val = list[nextIndex];
//start swapping values
list[nextIndex] = list[i];
list[i] = val;
}
}
}
}