如何在 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/