类<类型>在 C# 中类型>
我有一个类,希望将其作为列表使用:例如 List
我有一个 Randomizor 类,它将采用将被洗牌的集合数据类型。我怎样才能这样做呢?
class Randomizor<T>
{
public Randomizor()
{
}
public Array Shuffle(Array toShuffle)
{
}
}
I have a class and want to work with it as Lists: e.g. List<int>, List<string>, ... , List<T>
I have a class Randomizor which will take the collection data type that will be shuffled. How can I do so?
class Randomizor<T>
{
public Randomizor()
{
}
public Array Shuffle(Array toShuffle)
{
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
创建一个通用类,如下所示:
或者像这样:
Create a generic class like so:
Or like so:
不是很清楚的问题...你的意思是这样的吗?
Not very clear question... do you mean something like this?
编辑:经过一番挖掘后,我发现了两个高级实现,因此我建议优先使用它们。
用于此目的的扩展方法,之前已经建议过这里
我在下面包含了转述为 Shuffle 的代码。
一个有趣的解决方案改编自此 linq方法
原始答案但比编辑慢
如果您喜欢其中之一,您应该对链接的答案进行投票。
如果您非常关心随机性,可以升级到 RNG 来自加密 API 的算法,并为其注入一些不确定的值,例如从最近的鼠标活动生成的值。我怀疑这太过分了,而且会降低性能。
EDIT: I found two superior impementations after a little digging so I would suggest those in preference.
An extension method for this purpose and already been suggested previously here
I include the code paraphrased to Shuffle below.
And an interesting solution adapted from this linq approach
The orignal answer but slower than the edits
If you like one of these you should up vote the linked answer.
If you are very concerned about randomness, you could upgrade to one of the RNG algorithms from the Crypto API and seed it with some non deterministic value, like somthing generated from recent mouse activity. I suspect that would be overkill and it would degrade performance.
但是,您可能想要使用通用扩展方法
和用法:
However you may want to go for a generic extension method
and the usage:
也许像这样:
或者作为扩展方法
Maybe like this:
Or as an extension method