2012-01-30 31 views
1

我有這樣的結構如下。現在,我想交換2個結構。如何在c#中交換通用結構?

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; 
    }** 
} 

在Main方法試試這個:

 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 

上交換方法的參數比compilator achive不同。

+2

你不應該叫't2.Swap'嗎? – 2012-01-30 20:02:43

+0

你是否收到編譯錯誤,或者它只是智能錯誤? – thumbmunkeys 2012-01-30 20:03:09

+0

:)謝謝,我應該。 – mike00 2012-01-30 20:03:52

回答

5

這裏沒有必要輸出參數。只需把它定義爲:

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

那麼你可以這樣做:

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

Swap方法是有點混亂。通過引用傳入參數(out)並返回相同的參數沒有什麼意義。編譯器所期望的參數恰好就是這樣。你有一個Pair<int,String>(t1),所以T == int和U == String,並且你有第二個參數定義爲Pair<T,U>所以T必須是int和U必須是String

一個不太令人困惑的實施Swap要麼是這樣的:

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

或像這樣:

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

我寧願這樣:

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

然而,因爲有真的不需要參考任何東西。