你能通过走一棵对象树来阅读注释吗?

时间:2014-02-11 23:58:43

标签: c# annotations

考虑以下代码,是否有办法走对象树并确定所有方法的进度,重量和总成本?

假设我有自定义注释:

public enum ProgressWeight
  {
    ExtraLight,
    Light,
    Medium,
    Heavy,
    ExtraHeavy
  }

  [AttributeUsage(AttributeTargets.Method)]
  public class Progressable : Attribute
  {
    public ProgressWeight Weight { get; set; }

    public Progressable(ProgressWeight weight)
    {
      this.Weight = weight;
    }
  }

我想这样实现它:

public class Sumathig
{
  Foo CompositionObject;

  [Progressable(ProgressWeight.Light)]
  public void DoSomethingLight()
  {
    \\Do something that takes little time
  }

  [Progressable(ProgressWeight.ExtraHeavy)]
  public void DoSomeIntesiveWork()
  {
    CompositionObject = new Foo();
    CompositionObject.DoWork();
    CompositionObject.DoMoreWork();
  }
}

class Foo
{
  [Progressable(ProgressWeight.Medium)]
  public void DoWork()
  {
    \\Do some work
  }

  [Progressable(ProgressWeight.Heavy)]
  public void DoSomeMoreWork()
  {
    \\Do more work
  }
}

1 个答案:

答案 0 :(得分:1)

选项1 - 注释

您提供的示例表明您应该查看:

此方法使您可以使用可在运行时检索的元数据来注释代码。整个过程相对简单。有关反射的示例,请查看:

其他阅读

选项2

另一种方法是支持合成并将所需的元数据作为其中一个类的属性公开。这可能适用于插件样式架构。