c#3.0实现延迟赋值示例
本文导语: 延迟赋值主要有两点: 1.一个参数可能或可能没被赋值. 2.一个参数在一个函数中每次使用时可能被赋值. 如下面的这种情况: 代码如下:int Add(int x, int y){ return (2 + 1) + (1);} 使用Func,我们轻松实现,看代码: 代码如下:/// /...
延迟赋值主要有两点:
1.一个参数可能或可能没被赋值.
2.一个参数在一个函数中每次使用时可能被赋值.
如下面的这种情况:
int Add(int x, int y)
{
return (2 + 1) + (1);
}
使用Func,我们轻松实现,看代码:
///
/// LazyExpression
///
/// T
public class LazyExpression
{
Func thunk;
public LazyExpression(Func Thunk)
{
thunk = Thunk;
}
public T Evaluate()
{
return thunk();
}
}
///
/// LazyBoolExpression
///
public static class LazyBoolExpression
{
public static bool And(LazyExpression LHS, LazyExpression RHS)
{
return LHS.Evaluate() && RHS.Evaluate();
}
public static bool Or(LazyExpression LHS, LazyExpression RHS)
{
return LHS.Evaluate() == true ? true : RHS.Evaluate();
}
}
///
/// LazyMemoizedExpression
///
///
public class LazyMemoizedExpression
{
bool thunked;
T value;
Func thunk;
public LazyMemoizedExpression(Func Thunk)
{
thunked = false;
thunk = Thunk;
}
public T Evaluate()
{
if (!thunked)
{
value = thunk();
thunked = true;
}
return value;
}
}
LazyExpression类实现了基本的延迟赋值,LazyMemoizedExpression类实现了一次赋值,多次使用.
LazyBoolExpression实现逻辑表达式.
看UnitTest,一切就明白了
///
///Laziestheexpressiontest.
///
[TestCase]
publicvoidLazyExpressionTest()
{
varlme1=newLazyExpression(()=>2+1);
varlme2=newLazyExpression(()=>1);
Assert.AreEqual(4,Add(lme1,lme2));
}
///
///Addsthespecifiedx.
///
///Thex.
///They.
///result
privateintAdd(LazyExpressionx,LazyExpressiony)
{
returnx.Evaluate()+y.Evaluate();
}
///
///Laziestheexpressionwithlogic.
///
[TestCase]
publicvoidLazyExpressionWithLogic()
{
varexp1=newLazyExpression(()=>true);
varexp2=newLazyExpression(()=>true||false);
if(LazyBoolExpression.And(exp1,exp2))
{
Console.WriteLine("lazyand");
}
if(LazyBoolExpression.Or(exp1,exp2))
{
Console.WriteLine("lazyor");
}
}
///
///Laziesthememoizedexpressiontest.
///
[TestCase]
publicvoidLazyMemoizedExpressionTest()
{
varlme1=newLazyMemoizedExpression(()=>GetIntResult());
Assert.AreEqual(943,lme1.Evaluate());
Assert.AreEqual(943,lme1.Evaluate());
//output:
//1passed,0failed,0skipped,took2.80seconds(NUnit2.5).
}
///
///Comparestolazyexpressiontest.
///
[TestCase]
publicvoidCompareToLazyExpressionTest()
{
varlme1=newLazyExpression(()=>GetIntResult());
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;
}