C#Lazy属性 [英] C# Lazy property

查看:164
本文介绍了C#Lazy属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类中有一个Lazy属性:

  private Lazy< ISmtpClient> SmtpClient 
{
get
{
return new Lazy< ISmtpClient>(()=> _objectCreator.Create< ISmtpClient>(),true);
}
}

也是一个使用这种方法的方法:

  public void SendEmail(MailMessage message)
{
SmtpClient.Value.ServerName =testServer;
SmtpClient.Value.Port = 25;

SmtpClient.Value.Send(message);
}

但是在我的SmtpClient中,Send(string message)我在上面的SendEmail(MailMessage消息)方法中初始化为null。



如何解决此问题?



提前感谢。



p>当使用 Lazy< T> 时,会暴露实际类型的属性,并且有一个 Lazy< T> 实例。您不会在每次访问媒体资源时创建新的媒体:

  Lazy< ISmtpClient> _smtpClient = 
new Lazy< ISmtpClient>(()=> _objectCreator.Create< MySmtpClient>(),true);

private ISmtpClient SmtpClient
{
get
{
return _smtpClient.Value;
}
}

现在,第一次 SmtpClient 属性,对象创建者创建 MySmtpClient 的新实例。返回。



使用方法如下:

  public void SendEmail(MailMessage message)
{
SmtpClient.ServerName =testServer;
SmtpClient.Port = 25;

SmtpClient.Send(message);
}


I have a Lazy property in my class:

private Lazy<ISmtpClient> SmtpClient
    {
        get
        {
            return new Lazy<ISmtpClient>(() => _objectCreator.Create<ISmtpClient>(), true);
        }
    }

Also a methode that uses this proptery:

public void SendEmail(MailMessage message)
    {
        SmtpClient.Value.ServerName = "testServer";
        SmtpClient.Value.Port = 25;

        SmtpClient.Value.Send(message);
    }

But in my SmtpClient, in Send(string message) methode are all the propteries that i initialized in the above SendEmail(MailMessage message) methode, null.

How can i fix this?

Thanks in advance.

解决方案

You are using Lazy<T> wrong.

When using Lazy<T> you expose a property of the actual type and you have one Lazy<T> instance. You don't create a new one every time the property is accessed:

Lazy<ISmtpClient> _smtpClient =
    new Lazy<ISmtpClient>(() => _objectCreator.Create<MySmtpClient>(), true);

private ISmtpClient SmtpClient
{
    get
    {
        return _smtpClient.Value;
    }
}

Now, the first time the SmtpClient property is accessed, the object creator creates a new instance of MySmtpClient. This is returned. On subsequent calls, the same instance is returned.

The usage would be like this:

public void SendEmail(MailMessage message)
{
    SmtpClient.ServerName = "testServer";
    SmtpClient.Port = 25;

    SmtpClient.Send(message);
}

这篇关于C#Lazy属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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