如何实现延迟加载与PostSharp? [英] How to implement Lazy loading with PostSharp?
问题描述
我想实现与PostSharp属性延迟加载。
要长话短说,而不是写
SOMETYPE _field = NULL;
私人领域SOMETYPE
{
得到
{
如果(_field == NULL)
{
_field = LongOperation();
}
返回_field;
}
}
我想编写
[LazyLoadAspect]
私人对象字段
{
得到
{
返回LongOperation( );
}
}
所以,我确定我需要发出一些代码在类来生成为了实现测试支持字段,以及里面的getter方法。
通过PostSharp,我正在考虑重写 CompileTimeInitialize
,但我缺少知识,并得到了编译代码的句柄
编辑:
中的问题可以扩展到像任何参数的方法:
SOMETYPE _lazyLoadedField = NULL;
SOMETYPE LazyLoadableMethod()
{
如果(_lazyLoadedField == NULL)
{
//长时间操作代码...
_lazyLoadedField = SOMETYPE;
}
返回_lazyLoadedField;
}
将成为
[LazyLoad]
SOMETYPE LazyLoadableMethod()
{
//长时间操作代码...
返回SOMETYPE;
}
我们的意见后,我觉得我知道你现在想要什么。
[Serializable接口]
公共类LazyLoadGetter:LocationInterceptionAspect,IInstanceScopedAspect
{
私有对象后盾;
公共覆盖无效OnGetValue(LocationInterceptionArgs参数)
{
如果(后盾== NULL)
{
args.ProceedGetValue();
后盾= args.Value;
}
args.Value =后盾;
}
公共对象的CreateInstance(AdviceArgs adviceArgs)
{
返回this.MemberwiseClone();
}
公共无效RuntimeInitializeInstance()
{
}
}
测试代码
公开类测试
{
[LazyLoadGetter]
公众诠释myProperty的{{返回LongOperation(); }}
}
I would like to implement lazy loading on properties with PostSharp.
To make it short, instead of writing
SomeType _field = null;
private SomeType Field
{
get
{
if (_field == null)
{
_field = LongOperation();
}
return _field;
}
}
I would like to write
[LazyLoadAspect]
private object Field
{
get
{
return LongOperation();
}
}
So, I identify that I need to emit some code in the class to generate the backing field, as well as inside the getter method in order to implement the test.
With PostSharp, I was considering overriding CompileTimeInitialize
, but I am missing the knowledge to get a handle over the compiled code.
EDIT: The question can be extended to any parameterless method like:
SomeType _lazyLoadedField = null;
SomeType LazyLoadableMethod ()
{
if(_lazyLoadedField ==null)
{
// Long operations code...
_lazyLoadedField = someType;
}
return _lazyLoadedField ;
}
would become
[LazyLoad]
SomeType LazyLoadableMethod ()
{
// Long operations code...
return someType;
}
After our comments, I think I know what you want now.
[Serializable]
public class LazyLoadGetter : LocationInterceptionAspect, IInstanceScopedAspect
{
private object backing;
public override void OnGetValue(LocationInterceptionArgs args)
{
if (backing == null)
{
args.ProceedGetValue();
backing = args.Value;
}
args.Value = backing;
}
public object CreateInstance(AdviceArgs adviceArgs)
{
return this.MemberwiseClone();
}
public void RuntimeInitializeInstance()
{
}
}
Test code
public class test
{
[LazyLoadGetter]
public int MyProperty { get { return LongOperation(); } }
}
这篇关于如何实现延迟加载与PostSharp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!