如何使用PostSharp实现延迟加载?

rem*_*mio 3 c# aop lazy-loading postsharp

我想用PostSharp在属性上实现延迟加载.

简而言之,而不是写作

SomeType _field = null;
private SomeType Field
{
    get
    {
        if (_field == null)
        {
            _field = LongOperation();
        }
        return _field;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想写

[LazyLoadAspect]
private object Field
{
    get
    {
        return LongOperation();
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我确定我需要在类中发出一些代码来生成支持字段,以及在getter方法中为了实现测试.

使用PostSharp,我正在考虑覆盖CompileTimeInitialize,但我错过了处理已编译代码的知识.

编辑: 问题可以扩展到任何无参数的方法,如:

SomeType _lazyLoadedField = null;
SomeType LazyLoadableMethod ()
{
    if(_lazyLoadedField ==null)
    {
        // Long operations code...
        _lazyLoadedField = someType;
    }
    return _lazyLoadedField ;
}
Run Code Online (Sandbox Code Playgroud)

会成为

[LazyLoad]
SomeType LazyLoadableMethod ()
{
     // Long operations code...
     return someType;
}
Run Code Online (Sandbox Code Playgroud)

Dus*_*vis 5

在我们的评论之后,我想我现在知道你想要什么.

[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()
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

测试代码

public class test
    {
        [LazyLoadGetter]
        public int MyProperty { get { return LongOperation(); } }
    }
Run Code Online (Sandbox Code Playgroud)