开发者

Newbie Q on using reference and generics

开发者 https://www.devze.com 2022-12-21 19:28 出处:网络
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.

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();
    }
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号