Giriş
C# 7 ile referans dönmek mümkün.Açıklaması şöyle.
Şöyle yaparız.
Şöyle yaparız.
C# 7 ile referans dönmek mümkün.Açıklaması şöyle.
array dönülebilir. Açıklaması şöyle.You can only return refs that are “safe to return”: Ones that were passed to you, and ones that point into fields in objects.
Örnek - intReturning a local int variable instead of an array is not possible. int is a value type, and thus the variable gets out of scope at the end of the method, and thus a reference to it cannot be returned. That’s different with an array. An array is a reference type, and the array is allocated on the heap. An int within the array can be returned with the ref keyword.
Şöyle yaparız.
public ref int Find(int number, int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == number)
{
return ref numbers[i]; // return the storage location, not the value
}
}
throw new IndexOutOfRangeException($"{nameof(number)} not found");
}
Örnek - arrayŞöyle yaparız.
public ref string Find (int index)
{
string[] array = { "a", "b", "c", "d" };
return ref array[index];
}
Örnek - struct
Şöyle yaparız.// This size is 128 bytes, which is 2 or 4x larger than the size of a reference
public struct Coord
{
public long X, Y;
}
private Coord myCoord;
// This will return the Coord by value, meaning copying the full 128 bytes
public Coord GetCoordValue() => myCoord;
// This will return the Coord by reference, meaning copying only 32 or 64 bytes
public ref readonly Coord GetCoordRef() => ref myCoord;
Hiç yorum yok:
Yorum Gönder