Question

As part of an exercise I am trying to define a specific behavior for a generic class when used with a specific type. More precisely, I was wondering if it is possible to define a explicit casting operator for a generic type, i.e. from list<T> to int[]

No, I know I could simply define a method that does the work, however this is not the goal of the exercise.

Assuming the generic class list<T> I was trying to define the following explicit casting method

class list<T> {
...

    public static explicit operator int[](list<T> _t) where T : System.Int32 
    {
        // code handling conversion from list<int> to int[]
    }
}

This doesn't work however. Any ideas on how to make the compiler swallow this?

Était-ce utile?

La solution

Firstly, please change the name of the class to follow .NET conventions and avoid clashing with List<T>.

With that out of the way, you basically can't do what you're trying to do. You can define a conversion which is valid for all T, and then take different action for different cases. So you could write:

public static explicit operator T[](CustomList<T> input)

and then treat this differently if T is int. It wouldn't be nice to do the last part, but you could do it if you really wanted.

The members available on a particular generic type are the same whatever the type arguments (within the constraints declared at the point of type parameter declaration) - otherwise it's not really generic.

As an alternative, you could define an extension method in a top-level static non-generic type elsewhere:

public static int[] ToInt32Array(this CustomList<int> input)
{
    ...
}

That would allow you to write:

CustomList<int> list = new CustomList<int>();
int[] array = list.ToInt32Array();

Personally I'd find that clearer than an explicit conversion operator anyway.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top