当初始化延迟实例时,将参数传递给构造函数 [英] Pass parameters to constructor, when initializing a lazy instance

查看:151
本文介绍了当初始化延迟实例时,将参数传递给构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于当初始化延迟实例时,将参数传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆