延迟赋值主要有两点:
1.一个参数可能或可能没被赋值.
2.一个参数在一个函数中每次使用时可能被赋值.
如下面的这种情况:
使用Func<T>,我们轻松实现,看代码:
/// <summary>
/// LazyBoolExpression
/// </summary>
public static class LazyBoolExpression
{
public static bool And(LazyExpression<bool> LHS, LazyExpression<bool> RHS)
{
return LHS.Evaluate() && RHS.Evaluate();
}
public static bool Or(LazyExpression<bool> LHS, LazyExpression<bool> RHS)
{
return LHS.Evaluate() == true ? true : RHS.Evaluate();
}
}
/// <summary>
/// LazyMemoizedExpression
/// </summary>
/// <typeparam name="T"></typeparam>
public class LazyMemoizedExpression<T>
{
bool thunked;
T value;
Func<T> thunk;
public LazyMemoizedExpression(Func<T> Thunk)
{
thunked = false;
thunk = Thunk;
}
public T Evaluate()
{
if (!thunked)
{
value = thunk();
thunked = true;
}
return value;
}
}
LazyExpression<T>类实现了基本的延迟赋值,LazyMemoizedExpression<T>类实现了一次赋值,多次使用.
LazyBoolExpression实现逻辑表达式.
看UnitTest,一切就明白了
///<summary>
///Addsthespecifiedx.
///</summary>
///<paramname="x">Thex.</param>
///<paramname="y">They.</param>
///<returns>result</returns>
privateintAdd(LazyExpression<int>x,LazyExpression<int>y)
{
returnx.Evaluate()+y.Evaluate();
}
///<summary>
///Laziestheexpressionwithlogic.
///</summary>
[TestCase]
publicvoidLazyExpressionWithLogic()
{
varexp1=newLazyExpression<bool>(()=>true);
varexp2=newLazyExpression<bool>(()=>true||false);
if(LazyBoolExpression.And(exp1,exp2))
{
Console.WriteLine("lazyand");
}
if(LazyBoolExpression.Or(exp1,exp2))
{
Console.WriteLine("lazyor");
}
}
///<summary>
///Laziesthememoizedexpressiontest.
///</summary>
[TestCase]
publicvoidLazyMemoizedExpressionTest()
{
varlme1=newLazyMemoizedExpression<int>(()=>GetIntResult());
Assert.AreEqual(943,lme1.Evaluate());
Assert.AreEqual(943,lme1.Evaluate());
//output:
//1passed,0failed,0skipped,took2.80seconds(NUnit2.5).
}
///<summary>
///Comparestolazyexpressiontest.
///</summary>
[TestCase]
publicvoidCompareToLazyExpressionTest()
{
varlme1=newLazyExpression<int>(()=>GetIntResult());
Assert.AreEqual(943,lme1.Evaluate());
Assert.AreEqual(943,lme1.Evaluate());
//output:
//1passed,0failed,0skipped,took4.80seconds(NUnit2.5).
}
///<summary>
///Getstheintresult.
///</summary>
///<returns></returns>
privateintGetIntResult()
{
//currentthreadsleeptwosecond.
System.Threading.Thread.Sleep(2000);
return943;
}
新闻热点
疑难解答