c#3.0实现延迟赋值示例
延迟赋值主要有两点:
1.一个参数可能或可能没被赋值.
2.一个参数在一个函数中每次使用时可能被赋值.
如下面的这种情况:
int add(int x, int y)
{
return (2 + 1) + (1);
}
使用func<t>,我们轻松实现,看代码:
/// <summary>
/// lazyexpression
/// </summary>
/// <typeparam name="t">t</typeparam>
public class lazyexpression<t>
{
func<t> thunk;
public lazyexpression(func<t> thunk)
{
thunk = thunk;
}
public t evaluate()
{
return thunk();
}
}
/// <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>
///laziestheexpressiontest.
///</summary>
[testcase]
publicvoidlazyexpressiontest()
{
varlme1=newlazyexpression<int>(()=>2+1);
varlme2=newlazyexpression<int>(()=>1);
assert.areequal(4,add(lme1,lme2));
}
///<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;
}