【问题标题】:Using decorated attribute on method to call base class method在方法上使用修饰属性调用基类方法
【发布时间】:2012-08-18 01:29:08
【问题描述】:

是否可以创建自定义属性(MyAttribute),以便在运行时获取 Derived.MyProperty 实际上调用 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;
  }
}

这是从下面的 cmets 派生的解决方案。感谢所有评论者。

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

【问题讨论】:

  • 为什么不直接实现它们呢?
  • 我正在努力为 Base 用户简化开发过程。 Base 是在工作流中从节点到节点传递的类,在每个节点上,对节点处的处理器进行编码的开发人员可以将数据添加到接收到的 Base 对象中。我试图向开发人员隐藏添加的属性实际上包含在一个 xml 文档中,并且还以一种自然的方式为开发人员完成。
  • 这个问题可能会解决你的问题,如果你对 IL weaving [PostSharp aspect for property setters, calling generic method][1] [1]: stackoverflow.com/questions/246685/…

标签: c# .net custom-attributes


【解决方案1】:

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

【讨论】:

  • 非常感谢。 Unity 允许我完全按照我上面描述的方式进行操作。提供解决方案的是 TransparentProxyInterceptor、ICallHandler 和 PropertyMatchingRule 的组合。一个负面因素是,要“拦截”对象的属性,Unity 通过 Resolve 方法创建对象。我更愿意在先前创建的对象上打开或关闭拦截 - 还无法弄清楚。再次感谢。
猜你喜欢
  • 2010-09-06
  • 2013-09-02
  • 2012-10-30
  • 2021-03-17
  • 2012-12-02
  • 2019-12-20
  • 2015-12-03
  • 2018-05-12
  • 1970-01-01
相关资源
最近更新 更多