Pass parameters to constructor, when initializing a lazy instance

ⅰ亾dé卋堺 提交于 2020-01-10 09:34:51

问题


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);

My question is how to pass InstanceName to myClass constructor when we are using a lazy instance ?


回答1:


Try this:

Lazy<myClass> myLazy = new Lazy<myClass>(() => new myClass(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.




回答2:


Lazy has two ways to initialize. The first is using T's default ctor (parameterless)

the second is accepting an Func that has customer initialization logic. you should use the second overload as mentioned here

http://msdn.microsoft.com/en-us/library/dd642329.aspx




回答3:


You can't, Lazy<T> requires a parameterless constructor. You could use the Lazy<T>(Func<T>) constructor though, with a method that initializes the class.



来源:https://stackoverflow.com/questions/4414363/pass-parameters-to-constructor-when-initializing-a-lazy-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!