C#中的延迟执行 [英] Deferred execution in C#
问题描述
如何在C#中实现自己的延迟执行机制?
How could I implement my own deferred execution mechanism in C#?
例如,我有:
string x = DoFoo();
是否可以执行一些魔术操作,以使DoFoo在我使用" x之前不执行?
Is it possible to perform some magic so that DoFoo does not execute until I "use" x?
推荐答案
您可以使用lambda/delegates:
You can use lambdas/delegates:
Func<string> doit = () => DoFoo();
// - or -
Func<string> doit = DoFoo;
稍后,您可以像调用方法一样调用doit
:
Later you can invoke doit
just like a method:
string x = doit();
我认为您可以获得的最接近的东西是这样的:
I think the closest you can get is something like this:
Lazy<string> x = DoFoo;
string y = x; // "use" x
定义为Lazy<T>
与此类似(未经测试):
With a definition of Lazy<T>
similar to this (untested):
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>
的类型,因此无法将其与隐式转换运算符匹配.我们需要显式声明委托的类型,这使赋值语句更加冗长:
Unfortunately, it seems that the compiler's type inferencing algorithms can't auto-infer the type of the Func<T>
and so can't match it to the implicit conversion operator. We need to explicitly declare the delegate's type, which makes the assignment statements more verbose:
// 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#中的延迟执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!