我有如下结构.现在,我想要交换2结构.
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;
}**
}
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
Swap方法上的参数与compilator achive不同.
这里不需要输出参数.只需将其定义为:
public Pair<U, T> Swap()
{
return new Pair<U, T>(this.Snd, this.Fst);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
Pair<string, int> t2 = new Pair<string,int>("Anders",13);
Pair<int, string> t1 = t2.Swap();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
851 次 |
| 最近记录: |