当初始化延迟实例时,将参数传递给构造函数
问题描述:
public class myClass
{
public myClass(String InstanceName)
{
Name = InstanceName;
}
public String Name { get; set; }
}
// Now using myClass lazily I have:
Lazy<myClass> myLazy;
Console.WriteLine(myLazy.Value.Name);
我的问题是如何通过 InstanceName
My question is how to pass InstanceName
to myClass
constructor when we are using a lazy instance ?
答
尝试此操作时, myClass
:
Lazy<myClass> myLazy = new Lazy<myClass>(() => new myClass(InstanceName));
请记住,表达式是延迟计算的,因此如果您更改变量 InstanceName
在构造函数调用之前可能不会按照您的期望。
Remember that the expression is evaluated lazily, so if you change the value of the variable InstanceName
before the constructor is called it might not do what you expect.