C# 7 - Ref Returns and Ref Locals
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۱۲/۲۷ ۹:۳۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
static void PassByValueSample()
{
int a = 1;
PassByValue(a);
Console.WriteLine($"after the invocation of {nameof(PassByValue)}, {nameof(a)} = {a}");
}
static void PassByValue(int x)
{
x = 2;
} static void PassByReferenceSample()
{
int a = 1;
PassByReference(ref a);
Console.WriteLine($"after the invocation of {nameof(PassByReference)}, {nameof(a)} = {a}");
}
static void PassByReference(ref int x)
{
x = 2;
} static void OutSample()
{
Out(out int a);
Console.WriteLine($"after the invocation of {nameof(Out)}, {nameof(a)} = {a}");
}
static void Out(out int x)
{
x = 2;
} if (int.TryParse("42", out var result))
{
Console.WriteLine($"the result is {result}");
} int x = 3;
ref int x1 = ref x;
x1 = 2;
Console.WriteLine($"local variable {nameof(x)} after the change: {x}"); ref int i = sequence.Count();
ref int number1 = null; // ERROR ref int number2 = 42; // ERROR
static ref int ReturnByReference()
{
int[] arr = { 1 };
ref int x = ref arr[0];
return ref x;
} static ref int ReturnByReference2()
{
int[] arr = { 1 };
return ref arr[0];
} static ref int ReturnByReference3(ref int x)
{
x = 2;
return ref x;
} class Thing1
{
ref string _Text1; /* Error */
ref string Text2 { get; set; } /* Error */
string _text = "Text";
ref string Text3 { get { return ref _text; } } // Properties that return a reference are allowed
} private MyBigStruct[] array = new MyBigStruct[10];
private int current;
public ref MyBigStruct GetCurrentItem()
{
return ref array[current];
} namespace CS72Tests
{
public struct DataInfo
{
public double A;
}
public class RefReadonlyExamples
{
public DataInfo ReturnBiggestA(in DataInfo data1, in DataInfo data2)
{
return data1.A > data2.A ? data1 : data2;
}
public ref readonly DataInfo ReturnBiggestARefReadonly(in DataInfo data1, in DataInfo data2)
{
if (data1.A > data2.A)
{
return ref data1;
}
return ref data2;
}
public void TestingRefReadonly()
{
var data1 = new DataInfo { A = 0 };
var data2 = new DataInfo { A = 100 };
var biggest = ReturnBiggestA(data1, data2);
biggest.A = 42;
var biggest2 = ReturnBiggestARefReadonly(data1, data2);
biggest2.A = 99;
ref readonly var biggest3 = ref ReturnBiggestARefReadonly(data1, data2);
biggest3.A = 99; // ERROR: The left-hand side of an assignment must be a variable, property or indexer
}
}
} public static void Add(ref readonly int x, ref readonly int y, ref int z)
{
z = x + y + z;
}