0

Considering the following code, is there a way to walk the object tree and determine all the methods with progress, their weight and an overall cost?

let's say I have a custom annotation:

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

And I want to implement it as such:

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
  }
}
Chris Hayes
  • 3,876
  • 7
  • 42
  • 72
  • You should be able to do this if you either iterate over an array of the `Type`s of the classes or `Expression`s of the methods involved... It seems a bit messy though. – Magus Feb 12 '14 at 00:03
  • The `annotation` is the wrong word in this case. Fix tag. They are `attributes`. – Hamlet Hakobyan Feb 12 '14 at 00:07
  • If you have information about `type`(metadata) then you have information all you need. Use reflection. – Hamlet Hakobyan Feb 12 '14 at 00:09
  • He knows how to access the metadata most likely, what he wanted was to walk the class tree. I don't think that's possible unless you use something like Roslyn. – Magus Feb 12 '14 at 00:11
  • if I have to use a compiler than it's unlikely I'll go this route. I need to weight methods and present progress via events. – Chris Hayes Feb 12 '14 at 00:16
  • Again, you can pass methods in expressions and get the information from them that way, or you can do it from the `Type`s that contain them. It isn't that difficult, unless you want it to be arbitrary. That's the only reason you'd use Roslyn. – Magus Feb 12 '14 at 00:18
  • does anyone know anything about interceptors and events via ioc? – Chris Hayes Feb 12 '14 at 06:14

1 Answers1

1

OPTION 1 - Annotations

The example you provided suggests that you should take a look at:

This approach enables you to annotate your code with meta data which is retrievable at run-time. The entire process is relatively straight forward. For an example of reflection, take a look at:

ADDITIONAL READING

OPTION 2

An alternative approach is to favor composition and expose the required meta data as a property on one of your classes. This might work well for a plug-in style architecture.

Community
  • 1
  • 1
Pressacco
  • 2,815
  • 2
  • 26
  • 45