如果C#有一个懒惰的关键词 [英] Should C# have a lazy key word

查看:235
本文介绍了如果C#有一个懒惰的关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果C#有一个懒惰的关键字,使延迟初始化更容易?

Should C# have a lazy keyword to make lazy initialization easier?

例如。

    public lazy string LazyInitializeString = GetStringFromDatabase();

而不是


推荐答案

我不知道一个关键字,但它现在有一个的 System.Lazy< T> 类型。

I don't know about a keyword but it now has a System.Lazy<T> type.

  • 这是官方的一部分框架4.0
  • 它允许一个成员 A值的延迟加载。
  • 它支持拉姆达EX pression 方法来提供一个值。
  • It is officially part of .Net Framework 4.0.
  • It allows lazy loading of a value for a member.
  • It supports a lambda expression or a method to provide a value.
public class ClassWithLazyMember
{
    Lazy<String> lazySource;
    public String LazyValue
    {
        get
        {
            if (lazySource == null)
            {
                lazySource = new Lazy<String>(GetStringFromDatabase);
                // Same as lazySource = new Lazy<String>(() => "Hello, Lazy World!");
                // or lazySource = new Lazy<String>(() => GetStringFromDatabase());
            }
            return lazySource.Value;
        }
    }

    public String GetStringFromDatabase()
    {
        return "Hello, Lazy World!";
    }
}

测试:

var obj = new ClassWithLazyMember();

MessageBox.Show(obj.LazyValue); // Calls GetStringFromDatabase()
MessageBox.Show(obj.LazyValue); // Does not call GetStringFromDatabase()

在上面的测试code, GetStringFromDatabase()被调用一次。我想,这正是你想要的。

In above Test code, GetStringFromDatabase() gets called only once. I think that is exactly what you want.

具有@dthorpe和@Joe的意见后,我可以说的是下面是最短的也可以是:

After having comments from @dthorpe and @Joe, all I can say is following is the shortest it can be:

public class ClassWithLazyMember
{
    Lazy<String> lazySource;
    public String LazyValue { get { return lazySource.Value; } }

    public ClassWithLazyMember()
    {
        lazySource = new Lazy<String>(GetStringFromDatabase);
    }

    public String GetStringFromDatabase()
    {
        return "Hello, Lazy World!";
    }
}

由于以下不能编译:

public Lazy<String> LazyInitializeString = new Lazy<String>(() =>
{
    return GetStringFromDatabase();
});

和该属性是的类型懒&LT;字符串&GT; 不是字符串。你总是需要访问它使用 LazyInitializeString.Value 的价值。

And that property is type of Lazy<String> not String. You you always need to access it's value using LazyInitializeString.Value.

和,我打开了如何把它缩短的建议。

And, I am open for suggestions on how to make it shorter.

这篇关于如果C#有一个懒惰的关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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