I myself use an approach that reads the IL from an anonymous method (using Mono.Reflection
namespace) and grabs the info of the last token found in the anonymous method. This tends to be the only way to get information about things like the add_EventHandler
or set_Property
or captured local variables. To actual get properties I use expression trees.
The syntax that I use is Reflect.Member.InfoOf(Func memberfunc)
where Member is replaced with the type I'm interested in. It's verbose sure, but it lets a user know exactly what the code is trying to do. I also have Reflect.Member
styles for things like statics and constructors.
Here is the relevant code snippet::
internal static MemberInfo GetLastMemberOfType(MethodBase method, MemberTypes memberType)
{
var instructions = method.GetInstructions();
var operandtype = memberType == MemberTypes.Field ? OperandType.InlineField : OperandType.InlineMethod;
for (int i = instructions.Count-1; i > -1 ; i--)
{
if (instructions[i].OpCode.OperandType == operandtype)
{
return instructions[i].Operand as MemberInfo;
}
}
return null;
}
Does it replace string based reflection? Absolutely not. Does it make my code safer while I'm refactoring interfaces and what not? Absolutely.
Will it ship with the product I'm working on? Probably not.