延迟赋值主要有两点:
1.一个参数可能或可能没被赋值.
2.一个参数在一个函数中每次使用时可能被赋值.
如下面的这种情况:
复制代码 代码如下:
int Add(int x, int y)
{
return (2 + 1) + (1);
}
使用Func
复制代码 代码如下:
///
/// Lazyexpression
///
///
public class Lazyexpression
{
Func
public Lazyexpression(Func
{
thunk = Thunk;
}
public T evaluate()
{
return thunk();
}
}
///
/// LazyBoolexpression
///
public static class LazyBoolexpression
{
public static bool And(Lazyexpression
{
return LHS.evaluate() && RHS.evaluate();
}
public static bool Or(Lazyexpression
{
return LHS.evaluate() == true ? true : RHS.evaluate();
}
}
///
/// LazyMemoizedexpression
///
///
public class LazyMemoizedexpression
{
bool thunked;
T value;
Func
public LazyMemoizedexpression(Func
{
thunked = false;
thunk = Thunk;
}
public T evaluate()
{
if (!thunked)
{
value = thunk();
thunked = true;
}
return value;
}
}
Lazyexpression
LazyBoolexpression实现逻辑表达式.
看UnitTest,一切就明白了
复制代码 代码如下:
///
///Laziestheexpressiontest.
///
[TestCase]
publicvoidLazyexpressionTest()
{
varlme1=newLazyexpression
varlme2=newLazyexpression
Assert.AreEqual(4,Add(lme1,lme2));
}
///
///Addsthespecifiedx.
///
///
///
///
privateintAdd(Lazyexpression
{
returnx.evaluate()+y.evaluate();
}
///
///Laziestheexpressionwithlogic.
///
[TestCase]
publicvoidLazyexpressionWithLogic()
{
varexp1=newLazyexpression
varexp2=newLazyexpression
if(LazyBoolexpression.And(exp1,exp2))
{
Console.WriteLine("lazyand");
}
if(LazyBoolexpression.Or(exp1,exp2))
{
Console.WriteLine("lazyor");
}
}
///
///Laziesthememoizedexpressiontest.
///
[TestCase]
publicvoidLazyMemoizedexpressionTest()
{
varlme1=newLazyMemoizedexpression
Assert.AreEqual(943,lme1.evaluate());
Assert.AreEqual(943,lme1.evaluate());
//output:
//1passed,0failed,0skipped,took2.80seconds(NUnit2.5).
}
///
///Comparestolazyexpressiontest.
///
[TestCase]
publicvoidCompareToLazyexpressionTest()
{
varlme1=newLazyexpression
Assert.AreEqual(943,lme1.evaluate());
Assert.AreEqual(943,lme1.evaluate());
//output:
//1passed,0failed,0skipped,took4.80seconds(NUnit2.5).
}
///
///Getstheintresult.
///
///
privateintGetIntResult()
{
//currentthreadsleeptwosecond.
System.Threading.Thread.Sleep(2000);
return943;
}



