c# - C#中的延迟执行

标签 c# deferred-execution

如何在 C# 中实现我自己的延迟执行机制?

例如我有:

string x = DoFoo();

是否可以施展魔法,让 DoFoo 在我“使用”x 之前不执行?

最佳答案

您可以使用 lambdas/委托(delegate):

Func<string> doit = () => DoFoo();
//  - or -
Func<string> doit = DoFoo;

稍后您可以调用 doit就像一个方法:

string x = doit();

我想你能得到的最接近的是这样的:

Lazy<string> x = DoFoo;

string y = x; // "use" x

定义为Lazy<T>类似于此(未经测试):

public class Lazy<T>
{
    private readonly Func<T> func;
    private bool hasValue;
    private T value;

    public Lazy(Func<T> func)
    {
        this.func = func;
        this.hasValue = false;
    }

    public static implicit operator Lazy<T>(Func<T> func)
    {
        return new Lazy<T>(func);
    }

    public static implicit operator T(Lazy<T> lazy)
    {
        if (!lazy.hasValue)
        {
            lazy.value = lazy.func();
            lazy.hasValue = true;
        }
        return lazy.value;
    }
}

不幸的是,编译器的类型推断算法似乎无法自动推断 Func<T> 的类型。因此无法将其与隐式转换运算符匹配。我们需要显式声明委托(delegate)的类型,这使得赋值语句更加冗长:

// none of these will compile...
Lazy<string> x = DoFoo;
Lazy<string> y = () => DoFoo();
Lazy<string> z = delegate() { return DoFoo(); };

// these all work...
Lazy<string> a = (Func<string>)DoFoo;
Lazy<string> b = (Func<string>)(() => DoFoo());
Lazy<string> c = new Func<string>(DoFoo);
Lazy<string> d = new Func<string>(() => DoFoo());
Lazy<string> e = new Lazy<string>(DoFoo);
Lazy<string> f = new Lazy<string>(() => DoFoo);

关于c# - C#中的延迟执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1402923/

相关文章:

c# - 设计应用程序范围的日志记录系统的准则是什么?

python - 扭曲: `defer.execute` 和 `threads.deferToThread` 之间的区别

LINQ:使用 IEnumerable.Count() 或 IList.Count 以获得更好的性能

linq - 这个扩展方法是否有效地实现了我的 IQueryable?

C# 从 DataGridView 获取行

c# - 如何在C#中设置ushort的最左和最右位

c# - 为什么 IntelliSense 认为我字典中的值是动态的?

javascript - Rails 3 - 如何推迟 JavaScript 的解析

javascript - HTML 注入(inject)时使用 CDN 或外部域的内联脚本后执行脚本文件

c# - 如何保留数据的旧值和新值?