Question

how can I write this C# method

public bool CheckIsLocal()
{
    return HttpContext.Current.Request.IsLocal;
}

using C# Reflection.Emit?

this method is just a example, my intention is discover how to write code to access related members using C# Reflection.Emit.

Was it helpful?

Solution

public Func<bool> GenerateCheckIsLocal() {

            var dynamicMethod = new DynamicMethod("CheckIsLocal", typeof(bool), Type.EmptyTypes, true);

            var il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Call, typeof(HttpContext).GetProperty("Current").GetMethod);
            il.Emit(OpCodes.Call, typeof(HttpContext).GetProperty("Request").GetMethod);
            il.Emit(OpCodes.Call, typeof(HttpRequest).GetProperty("IsLocal").GetMethod);
            il.Emit(OpCodes.Ret);

            return dynamicMethod.CreateDelegate(typeof(Func<bool>)) as Func<bool>;
        }

Something like this should work i think.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top