c# generic, covering both arrays and lists?

前端 未结 6 1426
春和景丽
春和景丽 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:42

    The answer is to use the original code!

    This ought to be the only question on StackOverflow where the question itself illustrates significantly better code than any of the provided answers. All suggested answers encourage the use of an interface, which will imply a significant performance hit. Do not use those solutions in production code!

    Given that the question is tagged unity3d it is apparent that he code will be part of a game. In a game, the last thing you want is intermittent stuttering due to garbage collection. Typically, in Unity, you want enumerators to be extremely performant. Which brings me to the answer itself:

    Do NOT use interfaces for enumeration

    Unless you really have to. The List and T[] types have highly optimized value-typed enumerators. Once you cast your type to an interface, you will revert to the non-optimized reference-typed version. Every call to the non-optimized version of GetEnumerator() will produce garbage, adding up to the stuttering that will later take place (trust me) when the garbage collector collects those allocated objects.

    • Optimized version of List.GetEnumerator() here.
    • Non-optimized version of IEnumerable.GetEnumerator() here.

    For details, see my other answer.

提交回复
热议问题