st0*_*0ve 2 c# lazy-initialization .net-core
我在使用本文档class
中描述的方法初始化属性时遇到问题。
样本:
public class MyClass
{
private Lazy<string> _lazyString;
public MyClass()
{
_lazyString = new Lazy<string>(() => "hello world");
}
public string MyString => _lazyString.Value;
}
Run Code Online (Sandbox Code Playgroud)
当我调试时,我可以看到它_lazyString
的布尔值在我访问该属性之前就已IsCreated
设置为。最近的C#迭代中有什么变化吗?true
MyString
我的目标框架是netcoreapp3.1
按预期工作。
正如 @Progman 所指出的,使用调试器进行测试的问题在于,通过悬停该值会触发惰性操作。
要真正测试这种情况下的惰性,您可以使用 Lazy.IsValueCreated 属性。
通过下面的代码就可以看到
static void Main(string[] args)
{
MyClass c = new MyClass();
Console.WriteLine($"MyString not yet called.");
Console.WriteLine($"Is value created? {c.IsValueCreated}");
var s = c.MyString;
Console.WriteLine($"MyString called.");
Console.WriteLine($"Is value created? {c.IsValueCreated}");
}
public class MyClass
{
private Lazy<string> _lazyString;
public MyClass()
{
_lazyString = new Lazy<string>(() => "hello world");
}
public string MyString => _lazyString.Value;
public bool IsValueCreated => _lazyString.IsValueCreated;
}
Run Code Online (Sandbox Code Playgroud)
输出:
MyString not yet called.
Is value created? False
MyString called.
Is value created? True
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1791 次 |
最近记录: |