[英]How swap generic structure in c#?
我下面有这样的结构。 现在,我想交换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;
}**
}
在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
交换方法的参数不同于编译器的参数。
这里不需要out参数。 只需将其定义为:
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();
您的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;
}
但是,因为实际上没有必要通过引用传递任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.