标签: dynamicmethod

根据数据库中的数据动态调用C#方法

我的老板让我调查计算引擎.实际上,用户将拥有可以进行计算的数据表.他们还可以根据我们强制执行的某些限制来构建自己的计算(然后将构建的计算存储在数据库中)

是否可以在C#中调用特定方法,具体取决于数据库中存储的内容?因此,如果数据库说,计算应执行标准偏差.当我们从数据库中获取该信息时,是否可以调用我们将在C#中使用的标准偏差方法?

我希望这很清楚.

c# dynamicmethod

5
推荐指数
1
解决办法
6328
查看次数

不使用ref关键字替换参数的ref(使用IL)

我希望能够替换参数的对象引用,而不必使用ref关键字.

我避免使用ref的原因是保留了查找Add(T item)方法的集合初始化程序调用,我需要让集合类用它的接口的不同实现替换引用.

我尝试了几种不同的方法来做到这一点.首先,我尝试使用未记录的关键字__makeref,__refvalue并且__reftype.

其次,我尝试DynamicMethod用一些IL 来创建一个IL,它试图模仿我从一个带有ref参数的反汇编类似调用中观察到的东西.

以下是一些演示代码:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Reflection.Emit;
using System.Reflection;
interface IRecord
{
    string Name { get;}
}
class ImpA : IRecord
{
    public string Name { get { return "Implementation A"; } }
}
class ImpB : IRecord
{
    public string Name { get { return "Implementation B"; } }
}
class RecordList<T> : IEnumerable<T>
{
    //// Standard Add method (of course …
Run Code Online (Sandbox Code Playgroud)

c# il cil ref dynamicmethod

4
推荐指数
1
解决办法
495
查看次数

当发出方法的代码时,取消装箱Nullable会使评估堆栈处于意外(对我)状态

概述(请原谅我如此详细,但我宁愿它太多而不是太少):我正在尝试以这样的方式编辑Dapper源代码,以便从数据库中读取任何DateTime或Nullable ,其DateTime.Kind属性始终设置为DateTimeKind.Utc.

在我们的系统中,来自前端的所有DateTime都保证是UTC时间,并且数据库(Sql Server Azure)将它们存储为UTC中的DateTime类型(我们不使用DateTimeOffsets,我们总是确保DateTime在将其存储在数据库中之前是UTC.)

我一直在阅读有关如何使用ILGenerator.Emit(...)生成DynamicMethods代码的所有内容,并且感觉我对它如何与评估堆栈,本地人等一起工作有很好的理解.在我努力解决这个问题问题,我已经编写了一些代码示例,以帮助我实现最终目标.我写了一个DynamicMethod来取一个DateTime作为参数,调用DateTime.SpecifyKind,返回值.然后与DateTime相同?type,使用其Nullable.Value属性获取SpecifyKind方法的DateTime.

这就是我的问题所在:在dapper中,DateTime(或DateTime?我实际上并不知道,但是当我把它视为我要么得不到我想要的时候)是盒装的.所以,当我尝试使用OpCodes.Unbox或OpCodes.Unbox_Any,然后把结果作为要么日期时间或日期时间?我得到一个VerificationException:操作可能会破坏运行.

显然我错过了一些关于拳击的重要内容,但我会给你我的代码示例,也许你可以帮助我让它工作.

这有效:

    [Test]
    public void Reflection_Emit_Test3()
    {
        //Setup
        var dm = new DynamicMethod("SetUtc", typeof(DateTime?), new Type[] {typeof(DateTime?)});

        var nullableType = typeof(DateTime?);

        var il = dm.GetILGenerator();

        il.Emit(OpCodes.Ldarga_S, 0); // [DateTime?]
        il.Emit(OpCodes.Call, nullableType.GetProperty("Value").GetGetMethod()); // [DateTime]
        il.Emit(OpCodes.Ldc_I4, (int)DateTimeKind.Utc); // [DateTime][Utc]
        il.Emit(OpCodes.Call, typeof(DateTime).GetMethod("SpecifyKind")); //[DateTime]
        il.Emit(OpCodes.Newobj, nullableType.GetConstructor(new[] {typeof (DateTime)})); //[DateTime?]
        il.Emit(OpCodes.Ret);

        var meth = (Func<DateTime?, DateTime?>)dm.CreateDelegate(typeof(Func<DateTime?, DateTime?>));

        DateTime? now = DateTime.Now;

        Assert.That(now.Value.Kind, Is.Not.EqualTo(DateTimeKind.Utc));

        //Act

        var nowUtc = meth(now);

        //Verify

        Assert.That(nowUtc.Value.Kind, Is.EqualTo(DateTimeKind.Utc));
    }
Run Code Online (Sandbox Code Playgroud)

我得到了我期望的东西.好极了!但它还没有结束,因为我们已经拆箱了......

    [Test]
    public void Reflection_Emit_Test4()
    { …
Run Code Online (Sandbox Code Playgroud)

c# unboxing reflection.emit dynamicmethod dapper

4
推荐指数
1
解决办法
671
查看次数

如何从 il 生成器调用 Action&lt;string, bool&gt;

在此示例代码中,我试图从 il 生成器调用匿名操作。我不确定是否以及如何加载对委托的引用以及如何调用它。如果OnFunctionCall是静态方法而不是属性,我可以做到。

public delegate void TestDelegate();

public static class ExampleOne
{
    public static Action<string, bool> OnFunctionCall
        => (message, flag) => Console.WriteLine("Example");
}

public static class ExampleTwo
{
    public static TType CreateDelegate<TType>(Action<string, bool> onFunctionCall)
        where TType : class
    {
        var method = new DynamicMethod($"{Guid.NewGuid()}", typeof(void), Type.EmptyTypes, typeof(TType), true);

        ILGenerator il = method.GetILGenerator();

        // Emit some code that invoke unmanaged function ...

        // loading the first string argument
        il.Emit(OpCodes.Ldstr, method.Name);

        // not sure here how to load boolean value …
Run Code Online (Sandbox Code Playgroud)

c# reflection ilgenerator dynamicmethod

4
推荐指数
1
解决办法
672
查看次数

为什么这个DynamicMethod(ldarg.1,newobj,ret)会触发VerificationException?

我有这个方法,它在一个动态工厂方法中包装一个构造函数:

static Func<TArg1, TResult> ToFactoryMethod<TArg1, TResult>(this ConstructorInfo ctor)
    where TResult : class
{
    var factoryMethod = new DynamicMethod(
         name:           string.Format("_{0:N}", Guid.NewGuid()),
         returnType:     typeof(TResult), 
         parameterTypes: new Type[] { typeof(TArg1) });

    ILGenerator il = factoryMethod.GetILGenerator();
    il.Emit(OpCodes.Ldarg_1);
    il.Emit(OpCodes.Newobj, ctor);
    il.Emit(OpCodes.Ret);

    return (Func<TArg1, TResult>)
         factoryMethod.CreateDelegate(typeof(Func<TArg1, TResult>));
}
Run Code Online (Sandbox Code Playgroud)

但是,下面的代码抛出一个VerificationException.Invoke(…):

ConstructorInfo ctor = typeof(Uri).GetConstructor(new Type[] { typeof(string) });
Func<string, Uri> uriFactory = ctor.ToFactoryMethod<string, Uri>();
Uri uri = uriFactory.Invoke("http://www.example.com");
Run Code Online (Sandbox Code Playgroud)

如果我更换ldarg.1,则不会抛出异常; newobj <ctor>ldnull,所以这个问题必须由这两个IL指令造成的.进一步的实验表明错误在于ldarg.1.(我用ldstr <string>上面的具体例子替换了它.)

有谁看到这些IL指令有什么问题?

c# reflection reflection.emit dynamicmethod verificationexception

3
推荐指数
1
解决办法
837
查看次数

如何创建回调(添加为动态参数,一个函数)?

我正在创建此方法/函数,我需要实现回调.我的意思是,我需要添加一个动态参数,一个函数.我读过几篇文章但我无法理解如何获得它.任何想法或使用的例子?

public void httpReq (final String url, final Object postData, String callbackFunct, Object callbackParam,String callbackFailFunct) {
    if (postData == null || postData == "") {
        //GET
        Thread testGET = new Thread(new Runnable() {
            @Override
            public void run() {
                StringBuilder builder = new StringBuilder();
                HttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                ....
                }
        }
    } else {
        //POST
        Thread testPOST = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpGet httpPost = new HttpPost(url);
                ....
                }
        } …
Run Code Online (Sandbox Code Playgroud)

java android function callback dynamicmethod

3
推荐指数
1
解决办法
6582
查看次数

表达式在同一属性上将一个对象映射到另一个对象

我正在尝试使用Expression此代码创建一个简单的映射器:

public static class MyUtility {

    public static Action<TSource, TTarget> BuildMapAction<TSource, TTarget>(IEnumerable<PropertyMap> properties) {

        var sourceInstance = Expression.Parameter(typeof(TSource), "source");
        var targetInstance = Expression.Parameter(typeof(TTarget), "target");

        var statements = BuildPropertyGettersSetters(sourceInstance, targetInstance, properties);

        Expression blockExp = Expression.Block(new[] { sourceInstance, targetInstance }, statements);

        if (blockExp.CanReduce)
            blockExp = blockExp.ReduceAndCheck();
        blockExp = blockExp.ReduceExtensions();

        var lambda = Expression.Lambda<Action<TSource, TTarget>>(blockExp, sourceInstance, targetInstance);

        return lambda.Compile();
    }

    private static IEnumerable<Expression> BuildPropertyGettersSetters(
        ParameterExpression sourceInstance,
        ParameterExpression targetInstance,
        IEnumerable<PropertyMap> properties) {

        var statements = new List<Expression>();

        foreach (var property in properties) …
Run Code Online (Sandbox Code Playgroud)

c# linq lambda expression-trees dynamicmethod

3
推荐指数
1
解决办法
726
查看次数

如何将自定义属性添加到DynamicMethod生成的方法?

我正在玩DynamicMethod表达树编译(在DynamicMethod内部使用).

然后我想知道是否有一种方法可以为生成的方法添加自定义属性.我用Google搜索,但我找不到办法.我知道可以使用CodeDom,但我想使用DynamicMethod.

有人提到类型描述符,但我不确定它是否有帮助.

有谁知道为使用生成的方法定义自定义属性的方法DynamicMethod

.net c# custom-attributes dynamicmethod

2
推荐指数
1
解决办法
925
查看次数

使用Reflection.Emit的奇怪参数序列

我最近一直在关注Reflection.Emit.我写了一个简单的程序,它生成一个DynamicMethod,它简单地调用另一个具有相同参数的方法

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        p.Test();
    }

    public delegate void TestHandler(int a, int b, int c, int d, int e, int f);

    public void Test()
    {
        DynamicMethod method = new DynamicMethod(string.Empty, typeof(void), new[] { typeof(Int32), typeof(Int32), typeof(Int32), typeof(Int32), typeof(Int32), typeof(Int32) }, typeof(Program));


        MethodInfo method1 = typeof(Program).GetMethod("Question",BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,null,new Type[]{typeof(Int32),typeof(Int32),typeof(Int32),typeof(Int32),typeof(Int32),typeof(Int32)},null);
        MethodInfo method2 = typeof(MethodBase).GetMethod("GetCurrentMethod", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
        MethodInfo method3 = typeof(Console).GetMethod("WriteLine", BindingFlags.Static …
Run Code Online (Sandbox Code Playgroud)

c# reflection reflection.emit dynamicmethod

1
推荐指数
1
解决办法
1657
查看次数

如何在DynamicMethod Emit中表示typeof(Int32&)类型

我有以下代码:

    delegate void RefAction(ref Int32 i);// use ref keyword
    static RefAction CreateRefGenerator(){
        // How to represent typeof(Int32&)type in here??
        Type[] types ={ typeof(Int32)};
        var dm = new DynamicMethod("RefAction"+Guid.NewGuid().ToString(), null, types, true);
        var il = dm.GetILGenerator();
        il.Emit(OpCodes.Nop);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldc_I4_S,10);
        il.Emit(OpCodes.Stind_I4);
        il.Emit(OpCodes.Ret);

        return (RefAction)dm.CreateDelegate(typeof(RefAction));
    }
Run Code Online (Sandbox Code Playgroud)

运行后,得到以下错误:

因为其签名或安全透明性与委托类型的签名或安全透明性不兼容.

以下正常工作:

  static RefAction CreateRefGenerator(){
        Type[] types = { typeof(Int32).MakeByRefType() };
        ...
  }
Run Code Online (Sandbox Code Playgroud)

c# cil dynamicmethod emit

1
推荐指数
1
解决办法
189
查看次数