يكشنبه, ۲۹ مرداد ۱۳۹۶، ۱۰:۵۰ ق.ظ
یک مثال جالب از ref
بدون استفاده از پارامتر ref شما قادر نخواهید بود متدی در کلاسی بنویسید تا مقدار دو متغیر را عوض کند. اما با استفاده از از پارامتر ref شما میتوانید این کار را بکنید.
class ValueSwap
{
public void Swap( ref int a,ref int b)
{
int t;
t = a;
a = b;
b = t;
}
}
class Program
{
static void Main(string[] args)
{
ValueSwap ob = new ValueSwap();
int a = 5;
int b = 3;
Console.WriteLine("a and b before method a: {0} b:{1}", a, b);
ob.Swap(ref a, ref b);
Console.WriteLine("a and b after method a: {0} b:{1}", a, b);
}
}
{
public void Swap( ref int a,ref int b)
{
int t;
t = a;
a = b;
b = t;
}
}
class Program
{
static void Main(string[] args)
{
ValueSwap ob = new ValueSwap();
int a = 5;
int b = 3;
Console.WriteLine("a and b before method a: {0} b:{1}", a, b);
ob.Swap(ref a, ref b);
Console.WriteLine("a and b after method a: {0} b:{1}", a, b);
}
}
۹۶/۰۵/۲۹