Newbie Q on using reference and generics
this is the first time I need to use generics and references and I'm having a difficult time of it. I know it's something obvious.
public class Program
{
void SWAP<T>(ref T a, ref T b) { T dum = a; a = b; b = dum; }
static void Main(string[] args)
{
double a = 1; double b = 2;
double c = SWAP(a,开发者_如何学Python b);
Console.Write(a.ToString());
Console.Read();
}
}
On debug "SWAP(a, b)" gives the error: The best overloaded method for 'Program.SWAP(ref double, ref double)' has some invalid arguments.
Many thanks for putting up with these types of questions, Victor
When calling a function that uses a ref value, you need to tell the compiler to take a ref. Also your SWAP doesn't return a value.
So the swap line should be
SWAP(ref a, ref b);
Yes.. you need to pass the values in with the ref tag
edited until it compiled
public class Program {
static void SWAP<T>( ref T a, ref T b ) {
T dum = a;
a = b;
b = dum;
}
static void Main( string[] args ) {
double a = 1; double b = 2;
SWAP<double>( ref a,ref b );
Console.Write( a.ToString() );
Console.Read();
}
}
精彩评论