Quantcast
Channel: James Wiseman » LINQ
Viewing all articles
Browse latest Browse all 5

Type Filtering and Method Invocation with Reflection and LINQ – Part 4

$
0
0

Continuing on from the last post where we define some custom attributes, let’s look at setting up a class AttributeUsers that will use these attributes.

Add a new class library to the main solution. This library will need to reference the custom attributes assembly.

Here’s the code:

namespace AttributeUsers
{
    [CustomClassLevel]
    public class AttributeUser
    {
        public void Setup() { /* setup actions */ }
        public void Teardown() { /* teardown actions */}

        [CustomMethodLevel]
        public void Message1()
        {
            Console.WriteLine("Message 1 Called");
        }

        [CustomMethodLevel]
        public void Message2()
        {
            Console.WriteLine("Message 2 Called");
        }
    }
}

Again, there’s nothing truly groundbreaking here, however let’s note a few points:

  • The class is decorated with [CustomClassLevel]
  • The class is decorated with [CustomMethodLevel].
  • As it’s an attribute, the ‘Attribute’ is implied at the end of the name. We could have said [CustomClassLevelAttribute] instead and got an identical result.
  • The methods emit a message to the console. Our goal will be to invoke these dynamically. They are parameterless for simplicity, however later we’ll look at passing data that is specified on the attribute.

You’ll also note the Setup and Teardown methods. Really, this is just a nod to the unit testing framework that we are trying to mimic, and serves no functional purpose. Later on, we’ll see that it’s not enough just to include a library in an assembly – we actually have to use something within it, otherwise the compiler omits it. When searching for assemblies that include attributes, we therefore must have used something in it in order for the Attribute Discovery algorithm to work.

Next up in part 5, we get the nuts and bolts of the attribute discovery, and how we leverage the reflection capabilities to do this.

 


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images