Pass parameters to constructor, when initializing a lazy instance

后端 未结 3 1304
醉酒成梦
醉酒成梦 2020-12-14 07:23
public class myClass
{
   public myClass(String InstanceName)
   {
      Name = InstanceName;
   }
   public String Name { get; set; }
}

// Now using myClass lazily         


        
相关标签:
3条回答
  • 2020-12-14 07:50

    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.

    0 讨论(0)
  • 2020-12-14 08:03

    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.

    0 讨论(0)
  • 2020-12-14 08:14

    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

    0 讨论(0)
提交回复
热议问题