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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top