¿Cómo intercambiar la estructura genérica en C #?

I have structure like this below. Now, I want swap 2 structures.

public struct Pair<T, U>
{
    public readonly T Fst;
    public readonly U Snd;

    public Pair(T fst, U snd)
    {
        Fst = fst;
        Snd = snd;
    }

    public override string ToString()
    {
        return "(" + Fst + ", " + Snd + ")";
    }

    **public Pair<U, T> Swap(out Pair<U, T> p1, Pair<T,U> p2)
    {
        p1 = new Pair<U, T>(p2.Snd, p2.Fst);

        return p1; 
    }**
}

In Main method try this:

        Pair<int, String> t1 = new Pair<int, string>();
        Pair<String, int> t2 = new Pair<string,int>("Anders",13);
        **t1.Swap(out t1,);** //compilator tells -> http://i.stack.imgur.com/dM6P0.png

Parameters on Swap method are different than compilator achive.

preguntado el 30 de enero de 12 a las 19:01

¿No deberías llamar? t2.Swap ? -

do you get a compilation error, or is it just the intellisense that is wrong? -

That's really confusing. Using t1 como una out parameter in a method being called on t1 isn't the kind of code I'd like to pick up. -

@spender That was my thinking exactly - I see no reason for an out parameter here... -

2 Respuestas

There is no need for out parameters here. Just define it as:

public Pair<U, T> Swap()
{
    return new Pair<U, T>(this.Snd, this.Fst);
}

Entonces puedes hacer:

Pair<string, int> t2 = new Pair<string,int>("Anders",13);
Pair<int, string> t1 = t2.Swap();

Respondido el 31 de enero de 12 a las 00:01

Tus Swap method is a bit confusing. It doesn't make much sense to pass in a parameter by reference (out) and then return the same parameter. The parameters the compiler expect are exactly right by the way. You have a Pair<int,String> (t1), so T == int and U == String and you have the second argument defined as Pair<T,U> so T must be int and U must be String.

A less confusing implementation of Swap would either look like this:

public static void Swap(out Pair<U, T> p1, Pair<T,U> p2)
{
    p1 = new Pair<U, T>(p2.Snd, p2.Fst);
}

o así:

public void Swap(out Pair<U,T> pSwapped)
{
     pSwapped = new Pair<U,T>(Snd,Fst);
}

Preferiría esto:

public Pair<U,T> Swap()
{
    Pair<U,T> rV = new Pair<U,T>(Snd,Fst);
    return rV;
}

however, because there is really no need to pass in anything by reference.

Respondido el 31 de enero de 12 a las 00:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.