c# generic, covering both arrays and lists?

前端 未结 6 1469
春和景丽
春和景丽 2021-01-04 01:10

Here\'s a very handy extension, which works for an array of anything:

public static T AnyOne(this T[] ra) where T:class
{
    int k = ra         


        
6条回答
  •  青春惊慌失措
    2021-01-04 01:44

    T[] and List both share the same interface: IEnumerable.

    IEnumerable however, does not have a Length or Count member, but there is an extension method Count(). Also there is no indexer on sequences, so you must use the ElementAt(int) extension method.

    Something along the lines of:

    public static T AnyOne(this IEnumerable source)
    {
        int endExclusive = source.Count();
        int randomIndex = Random.Range(0, endExclusive); 
        return source.ElementAt(randomIndex);
    }
    

提交回复
热议问题