ChenChong-Hub
12/4/2019 - 8:42 AM

EMIT

需要添加Castle.Core引用

class Program
    {
        static void Main(string[] args)
        {
            ProxyGenerator generator = new ProxyGenerator();
            var test = generator.CreateClassProxy<TestA>(new TestInterceptor());
            Console.WriteLine($"GetResult:{test.GetResult1(Console.ReadLine(), "画中人")}");
            test.GetResult2("test");
            test.GetResult3("test3");
            test.GetResult4("test4");

            Console.ReadLine();
        }
    }

    public class TestA
    {
        public virtual string GetResult1(string msg, string oStr)
        {
            string str = $"{DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss")}---{msg}---{oStr}";
            return str;
        }

        public virtual string GetResult2(string msg)
        {
            throw new Exception("throw Exception!");
        }

        public string GetResult3(string msg)
        {
            Console.WriteLine(msg);
            return msg;
        }

        public string GetResult4(string msg)
        {
            Console.WriteLine(msg);
            throw new Exception("throw Exception 4");
        }
    }

    public class TestInterceptor : StandardInterceptor
    {
        protected override void PreProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行前,入参:" + string.Join(",", invocation.Arguments));
        }

        protected override void PerformProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行中");
            try
            {
                base.PerformProceed(invocation);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected override void PostProceed(IInvocation invocation)
        {
            Console.WriteLine(invocation.Method.Name + "执行后,返回值:" + invocation.ReturnValue);
        }

        private void HandleException(Exception ex)
        {
            Console.WriteLine($"error: {ex.Message}");
        }
    }