0

是否可以创建一个自定义属性 (MyAttribute),以便在运行时获取 Derived.MyProperty 实际上调用 Base.GetProperty("MyProperty") 并且 Derived.MyProperty 的集合调用 Base.SetProperty("MyProperty", value )。

class Derived : Base
{
  [MyAttribute]
  string MyProperty { get; set;}
}

class Base
{
  XmlDoc _xmldoc;
  void SetProperty(string key, string value)
  {
    set key, value into _xmldoc;
  }
  string GetProperty(string key);
  {
    get key value from _xmldoc;
  }
}

这是从以下评论中得出的解决方案。感谢所有评论者。

public class WatchAttribute : HandlerAttribute
{
  public override ICallHandler CreateHandler(IUnityContainer container)
  {
    return new WatchHandler();
  }
}

public class WatchHandler : ICallHandler
{
  public int Order { get; set; }
  public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
  {
    Console.WriteLine(string.Format("Method '{0}' on object '{1}' was invoked.", 
    return getNext()(input, getNext);
  }
}

public class SomeAction : MarshalByRefObject
{
  [Watch]
  public string MyProperty1 { get; set; }

  public string MyProperty { get; set; }
}

class Program
{
  static void Main(string[] args)
  {
    SomeAction c = new SomeAction();
    IUnityContainer container = new UnityContainer()
      .AddNewExtension<Interception>();
    container.Configure<Interception>()
      .SetInterceptorFor<SomeAction>(new TransparentProxyInterceptor())
      .AddPolicy("WatchAttribute Policy")
      .AddMatchingRule(new PropertyMatchingRule("*", PropertyMatchingOption.GetOrSet));
    container.RegisterInstance<SomeAction>(c);
    c = container.Resolve<SomeAction>();

    c.MyProperty1 = "Hello";
    c.MyProperty = "Hello";
  }
}
4

1 回答 1

1

使用统一拦截会更好,因为它允许您拥有一个代理来包装您想要的方法并指定规则来过滤方法这里解释: http ://www.lm-tech.it/Blog/post/2011/10 /18/How-to-use-the-Unity-Interception-Extension.aspx 它允许您在不设置任何属性的情况下进行流程,并且您的开发人员只需遵循规则名称(例如,所有与您的 xmldoc 一起使用的属性)以 Xml_ 为前缀...

于 2012-08-18T02:06:54.653 回答