事后的想法似乎不起作用,简单的代码

时间:2012-05-15 18:29:56

标签: c# code-injection post-build-event aop afterthought

我编写了一段简单的代码来参与Afterthought,但它不起作用,我不明白为什么。其中很大一部分来自其他SO问题:How to implement simple Property Ammendment with Afterthought

using System;
using System.Collections.Generic;
using Afterthought;
namespace SecondAmendmentTest
{
    class Program
    {
        public class TestUser
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public bool HasChanged { get; set; }
            public void method()
            {
                Console.WriteLine("method");
            }
        }

        public class TestUserAmmendment<T> : Amendment<T, T> where T : TestUser
        {
            public TestUserAmmendment()
            {
                Properties
                    .AfterSet((instance, x, y, z, a) => instance.HasChanged = true);
                Methods.After(ExceptionMethod);
            }

            private object ExceptionMethod(T instance, string method, object[] parameters, object result)
            {
                throw new NotImplementedException();
            }
        }

        static void Main(string[] args)
        {
            TestUser tu = new TestUser();
            Console.WriteLine("Has changed: " + tu.HasChanged.ToString());
            Console.WriteLine("Performing changes...");
            tu.Id = 5;
            tu.FirstName = "name";
            tu.LastName = "lastname";
            Console.WriteLine("Has changed: " + tu.HasChanged.ToString());
            tu.method();
            Console.ReadKey();
        }
    }
}

它编译,但输出exe文件没有更改。我已经配置了post build事件。构建输出:

1>------ Rebuild All started: Project: SecondAmendmentTest, Configuration: Debug Any CPU ------
1>  SecondAmendmentTest -> C:\Users\Lukasz\Documents\Visual Studio 11\Projects\SecondAmendmentTest\SecondAmendmentTest\bin\Debug\SecondAmendmentTest.exe
1>  Amending SecondAmendmentTest.exe (5,559 seconds)
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

最后在运行后从应用程序输出:

C:\Users\Lukasz\Documents\Visual Studio 11\Projects\SecondAmendmentTest\SecondAmendmentTest\bin\Debug>SecondAmendmentTest.exe
Has changed: False
Performing changes...
Has changed: False
method

HasChanged属性未被修改,也未引发NotImplementedException。我正在使用Git的最新资料。你有一些想法为什么它不起作用?

编辑:这是完整的解决方案:SecondAmendmentTest.zip

2 个答案:

答案 0 :(得分:1)

我知道这是一年之后但是:

基于Willem van Ketwich的回答,在Afterthought.NET中实际上存在一个错误(监督?),如果没有修改父类型,则不允许修改嵌套类型。

我已经提交了pull request修复错误。

除了此修复程序之外,您还需要在嵌套类上使用[Amendment(typeof(TestUserAmmendment<>))]来触发修订。

答案 1 :(得分:0)

我通过做两件事来实现这个目标:

  • 将TestUser和TestUserAmmendment类移出本程序 所以他们没有嵌套。

  • 将属性[Amendment(typeof(TestUserAmmendment<>))]添加到 TestUser类。

可以找到工作解决方案here