在方法上使用deco属性来调用基类方法

时间:2012-08-18 01:29:09

标签: c# .net custom-attributes

是否可以创建自定义属性(MyAttribute),以便在运行时,Derived.MyProperty的get实际调用Base.GetProperty(“MyProperty”),Derived.MyProperty集合调用Base.SetProperty(“MyProperty” “,价值)。

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";
  }
}

1 个答案:

答案 0 :(得分:1)

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

相关问题