如果我正在创建一个对象并且我希望它只持续到当前代码块,之后它将被自动销毁(或至少标记为销毁),我可以使用scope
关键字:
using System;
class Program
{
public void Program()
{
let basicString = String("Basic String");
for (let i = 0 ; i < 4 ; i++)
{
let modifiedString = scope String(s);
if (i%2 == 0)
{
modifiedString.ToUpper();
}
else
{
modifiedString.ToLower();
}
Console.WriteLine(modifiedString);
// modifiedString is marked for destruction
}
}
}
但是,如果我需要将对象保留到块之后,例如对于整个方法或对于它创建的块之外的块,我该如何指定该范围?例如,如何确保字符串存在于下面的第二个循环中?
using System;
using System.Collections.Generic;
class Program
{
public void Program()
{
let basicString = String("Basic String");
let modifiedStringList = scope List<String>();
for (let i = 0 ; i < 4 ; i++)
{
let modifiedString = scope String(s);
if (i%2 == 0)
{
modifiedString.ToUpper();
}
else
{
modifiedString.ToLower();
}
modifiedStringList.Append(modifiedString);
Console.WriteLine(modifiedString);
// somehow prevent modifiedString from being marked for destruction
}
modifiedStringList.RemoveAt(1);
for (let s in modifiedStringList)
{
Console.WriteLine(s);
}
// allow all of the modifiedString to be marked for destruction here
}
}