【问题标题】:Can you read annotations by walking an object tree您可以通过遍历对象树来阅读注释吗
【发布时间】:2014-03-10 01:31:40
【问题描述】:

考虑以下代码,有没有办法遍历对象树并确定所有方法的进度、它们的权重和总成本?

假设我有一个自定义注释:

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

【问题讨论】:

  • 如果您遍历类的Types 或所涉及方法的Expressions 的数组,您应该能够做到这一点......虽然看起来有点混乱。
  • annotation 在这种情况下是错误的词。修复标签。他们是attributes
  • 如果你有关于type(metadata) 的信息,那么你就有了所有你需要的信息。使用反射。
  • 他最有可能知道如何访问元数据,他想要的是遍历类树。除非您使用 Roslyn 之类的东西,否则我认为这是不可能的。
  • 如果我必须使用编译器,我不太可能走这条路。我需要权衡方法并通过事件展示进度。

标签: c# annotations


【解决方案1】:

选项 1 - 注释

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

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

补充阅读

选项 2

另一种方法是支持组合并将所需的元数据公开为您的一个类的属性。这可能适用于 插件 风格的架构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    相关资源
    最近更新 更多