One interesting capability of .NET 4.5 is that we can customize our reflection context, overriding the default reflection behavior with the
CustomReflectionContext
class.
With it, we can control what properties and attributes are exposed by a class through reflection.
Here we will override the reflection behavior to provide additional attributes:
Create a new Visual Studio project of type Console Application named
caOverridingReflection
.In the References folder of the project, in the Solution Explorer, add a reference to the
System.Reflection.Context
assembly.Open the Program.cs file and add a
using
clause for system.reflection.using System.Reflection;
Next, add the
SomeClass
declaration:class SomeClass { //Nothing here.. }
Then add a method to visualize, through reflection, the attributes of a type:
public static void ShowAttributes(Type t) { foreach (Attribute a in t.GetCustomAttributes()) { Console.WriteLine(a); ...