Skip to content

Instantly share code, notes, and snippets.

@vkovalskiy
Created October 18, 2011 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkovalskiy/1294312 to your computer and use it in GitHub Desktop.
Save vkovalskiy/1294312 to your computer and use it in GitHub Desktop.
TNAPS Blog - Refactoring and Obfuscation of reflection code
public class SimpleClass
{
private readonly string theValue;
public SimpleClass(string value)
{
theValue = value;
}
public string Value
{
get { return theValue; }
}
internal static Type SimpleClassInfo
{
get { return typeof(SimpleClass); }
}
internal static PropertyInfo ValueProperty
{
get{ return SimpleClassInfo.GetProperty("Value", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); }
}
internal static FieldInfo ValueField
{
get{ return return SimpleClassInfo.GetField("theValue", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); }
}
internal static ConstructorInfo Constructor
{
get { return SimpleClassInfo.GetConstructor(new[] { typeof(string) }); }
}
}
static TMember Reflect<TDelegate, TMember>(Expression<TDelegate> memberAccess)
where TDelegate : class where TMember : MemberInfo
{
if (memberAccess.Body is MemberExpression)
return ((MemberExpression)memberAccess.Body).Member as TMember;
else if (memberAccess.Body is NewExpression)
return ((NewExpression)memberAccess.Body).Constructor as TMember;
else if (memberAccess.Body is MethodCallExpression)
return ((MethodCallExpression)memberAccess.Body).Method as TMember;
else return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment