Why can't System.Array be a type constraint?

后端 未结 2 753
忘掉有多难
忘掉有多难 2021-01-17 12:53

I\'m working on a small project with a few different types of arrays (e.g. double[], float[], int[]. For verification / testing / sani

相关标签:
2条回答
  • 2021-01-17 13:30

    If taken the question literally, it would be useless to have an Array constraint. It's the same as it's useless to have a ValueType constraint, as it actually doesn't check whether you use a value type as a generic argument, but whether the type you are passing is assignable to ValueType.
    So you can pass even Array as the generic argument and it's OK.

    What is actually useful is to have an array contraint allowing any type that derives from Array, but not Array itself:

    void Print<TArr>(TArr t) where TArr : array //or [*] or other fancy syntax
    

    Where T can be [], [,], [,,], [,,,], and so on. The only over non-generic Array parameter is that we know the element type of the array.

    Another way to solve this is to create a custom Array<T> class with implicit operator overloads of T[], T[,], T[,,] etc.

    Edit:
    There is no way to achieve this even in CIL (currently), because int[,] and Array don't differ in any interfaces or constructors. We need where T : Array but not Array itself contraint.

    0 讨论(0)
  • 2021-01-17 13:45

    The appropriate syntax to do what you want is this:

    void Print<T>(T[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write(array[i]);
        }
    }
    
    0 讨论(0)
提交回复
热议问题