c# 泛型,涵盖数组和列表? [英] c# generic, covering both arrays and lists?
问题描述
这是一个非常方便的扩展,它适用于任何array
:
Here's a very handy extension, which works for an array
of anything:
public static T AnyOne<T>(this T[] ra) where T:class
{
int k = ra.Length;
int r = Random.Range(0,k);
return ra[r];
}
不幸的是,它不适用于 List<>
任何内容.这是适用于任何 List<>
Unfortunately it does not work for a List<>
of anything. Here's the same extension that works for any List<>
public static T AnyOne<T>(this List<T> listy) where T:class
{
int k = listy.Count;
int r = Random.Range(0,k);
return listy[r];
}
事实上,有没有一种方法可以一次性泛化涵盖 array
和 List<>
的泛型?还是知道不可能?
In fact, is there a way to generalise generics covering both array
s and List<>
s in one go? Or is it know to be not possible?
答案甚至(喘气)是否可以包含Collection
s?
Could the answer even (gasp) encompass Collection
s?
PS,我很抱歉没有明确提到这是在 Unity3D 环境中.例如Random.Range"只是一个 Unity 调用(这很明显),AnyOne"是游戏编程中完全典型的扩展或调用.
PS, I apologize for not explicitly mentioning this is in the Unity3D milieu. For example "Random.Range" is just a Unity call (which does the obvious), and "AnyOne" is a completely typical extension or call in game programming.
显然,这个问题当然适用于任何 c# 环境.
Obviously, the question of course applies in any c# milieu.
推荐答案
事实上 T[]
和 List
之间最合适的通用接口适合你的情况是 IReadOnlyList
In fact the most appropriate common interface between T[]
and List<T>
for your case is IReadOnlyList<T>
public static T AnyOne<T>(this IReadOnlyList<T> list) where T:class
{
int k = list.Count;
int r = Random.Range(0,k);
return list[r];
}
正如在另一个答案中提到的,IList
也有效,但好的做法要求您从调用方请求该方法所需的最低限度功能,即在这种情况下是 Count
属性和 只读 索引器.
As mentioned in another answer, IList<T>
also works, but the good practice requires you to request from the caller the minimum functionality needed by the method, which in this case is Count
property and read only indexer.
IEnumerable
也可以工作,但它允许调用者传递一个非集合迭代器,其中 Count
和 ElementAt
扩展方法可以是非常低效 - 如Enumerable.Range(0, 1000000)
、数据库查询等
IEnumerable<T>
also works, but it allows the caller to pass a non collection iterator where Count
and ElementAt
extension methods could be highly inefficient - like Enumerable.Range(0, 1000000)
, database query etc.
2020 年,对于 Unity3D 程序员来说很快:当然,现在 .Net 的现代版本可以在 Unity 中使用!
2020, quick for Unity3D programmers: of course, nowadays modern versions of .Net are available in Unity!
这篇关于c# 泛型,涵盖数组和列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!