在 C# 中使用表达式创建通用委托

发布于 2024-12-11 02:42:51 字数 2229 浏览 0 评论 0原文

下面给出了两种创建委托来设置类中字段的方法。一种方法使用泛型,另一种则不使用。 这两种方法都返回一个委托并且它们工作正常。但是,如果我尝试使用在 CreateDelegate 方法中创建的委托,那么非泛型委托“del”就可以正常工作。我可以在 return 语句上放置一个断点,并通过编写 del(222) 来调用委托。但是如果我尝试通过编写 genericDel(434) 来调用通用委托“genericDel”,它会引发异常:

委托“System.Action”有一些无效参数

任何人都可以解释这个怪癖。

class test
{
    public double fld = 0;
}

public static void Main(string[] args)
{
    test tst = new test() { fld = 11 };

    Type myType = typeof(test);
    // Get the type and fields of FieldInfoClass.
    FieldInfo[] myFieldInfo = myType.GetFields(BindingFlags.Instance | BindingFlags.Public);
    var a = CreateDelegate<double>(myFieldInfo[0], tst);
    var b = CreateDelegate(myFieldInfo[0], tst);

    Console.WriteLine(tst.fld);

    b(5.0);
    Console.WriteLine(tst.fld);

    a(6.0);
    Console.WriteLine(tst.fld);
}

public static Action<T> CreateDelegate<T>(FieldInfo fieldInfo, object instance)
{
    ParameterExpression numParam = Expression.Parameter(typeof(T), "num");
    Expression a = Expression.Field(Expression.Constant(instance), fieldInfo);
    BinaryExpression assExp = Expression.Assign(a, numParam);

    Expression<Action<T>> expTree =
        Expression.Lambda<Action<T>>(assExp,
            new ParameterExpression[] { numParam });

    Action<T> genericDel = expTree.Compile();
    //try to invoke the delegate from immediate window by placing a breakpoint on the return below: genericDel(323)
    return genericDel;
}

public static Action<double> CreateDelegate(FieldInfo fieldInfo, object instance)
{
    ParameterExpression numParam = Expression.Parameter(typeof(double), "num");
    Expression a = Expression.Field(Expression.Constant(instance), fieldInfo);
    BinaryExpression assExp = Expression.Assign(a, numParam);

    Expression<Action<double>> expTree =
        Expression.Lambda<Action<double>>(assExp,
            new ParameterExpression[] { numParam });

    Action<double> del = expTree.Compile();
    //try to invoke the delegate from immediate window by placing a breakpoint on the return below: del(977)
    return del;
}

Given below are two methods which create a delegate to set a field in a class. One method uses generics and the other does not.
Both the methods return a delegate and they work fine. But if I try to use the delegate that has been created inside the CreateDelegate method, then the non-generic delegate 'del' works fine. I can place a breakpoint on the return statement and invoke the delegate by writting del(222). But If I try to invoke the generic delegate 'genericDel' by writting genericDel(434), it throws an exception:

Delegate 'System.Action' has some invalid arguments

Can anyone explain this quirk.

class test
{
    public double fld = 0;
}

public static void Main(string[] args)
{
    test tst = new test() { fld = 11 };

    Type myType = typeof(test);
    // Get the type and fields of FieldInfoClass.
    FieldInfo[] myFieldInfo = myType.GetFields(BindingFlags.Instance | BindingFlags.Public);
    var a = CreateDelegate<double>(myFieldInfo[0], tst);
    var b = CreateDelegate(myFieldInfo[0], tst);

    Console.WriteLine(tst.fld);

    b(5.0);
    Console.WriteLine(tst.fld);

    a(6.0);
    Console.WriteLine(tst.fld);
}

public static Action<T> CreateDelegate<T>(FieldInfo fieldInfo, object instance)
{
    ParameterExpression numParam = Expression.Parameter(typeof(T), "num");
    Expression a = Expression.Field(Expression.Constant(instance), fieldInfo);
    BinaryExpression assExp = Expression.Assign(a, numParam);

    Expression<Action<T>> expTree =
        Expression.Lambda<Action<T>>(assExp,
            new ParameterExpression[] { numParam });

    Action<T> genericDel = expTree.Compile();
    //try to invoke the delegate from immediate window by placing a breakpoint on the return below: genericDel(323)
    return genericDel;
}

public static Action<double> CreateDelegate(FieldInfo fieldInfo, object instance)
{
    ParameterExpression numParam = Expression.Parameter(typeof(double), "num");
    Expression a = Expression.Field(Expression.Constant(instance), fieldInfo);
    BinaryExpression assExp = Expression.Assign(a, numParam);

    Expression<Action<double>> expTree =
        Expression.Lambda<Action<double>>(assExp,
            new ParameterExpression[] { numParam });

    Action<double> del = expTree.Compile();
    //try to invoke the delegate from immediate window by placing a breakpoint on the return below: del(977)
    return del;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

っ〆星空下的拥抱 2024-12-18 02:42:51

我想我理解了这个问题;当委托的编译时类型是开放泛型类型时,您在从立即窗口调用泛型委托时遇到问题。
这是一个更简单的重现:

  static void Main() { Test<double>(); }

  static void Test<T>()
  {
        Action<T> genericDel = delegate { };
       // Place break-point here.
  }

现在,如果我尝试从 Test 方法中执行此委托(通过放置断点并使用立即窗口),如下所示:

genericDel(42D);

我收到以下错误:

Delegate 'System.Action<T>' has some invalid arguments

请注意, 不是像您所说的例外,而是编译时错误 CS1594。

请注意,此类调用在编译时同样会失败,因为没有从 doubleT 的隐式或显式转换。

有争议是立即窗口的一个缺点(在这种情况下它似乎不愿意使用额外的“运行时知识”来帮助您),但人们可以认为这是合理的行为,因为在编译时进行了等效的调用(在源代码中)也是非法的。但这确实是一个极端情况;立即窗口完全能够分配通用变量并执行其他在编译时非法的代码。也许罗斯林会让事情变得更加一致。

如果您愿意,您可以像这样解决这个问题:(

genericDel.DynamicInvoke(42D);

或)

((Action<double>)(object)genericDel)(42D);

I think I understood the issue; you are having problems invoking a generic delegate from the immediate window when the compile-time type of the delegate is an open generic type.
Here's a simpler repro:

  static void Main() { Test<double>(); }

  static void Test<T>()
  {
        Action<T> genericDel = delegate { };
       // Place break-point here.
  }

Now, if I try executing this delegate from within the Test method (by placing a break-point and using the immediate window) like this:

genericDel(42D);

I get the following error:

Delegate 'System.Action<T>' has some invalid arguments

Note that this not an exception like you have stated, but rather the 'immediate window version' of compile-time error CS1594.

Note that such a call would have failed equally at compile-time because there is no implicit or explicit conversion from double to T.

This is debatably a shortcoming of the immediate window (it doesn't appear to be willing to use additional 'run-time knowledge' to help you out in this case), but one could argue that it is reasonable behaviour since an equivalent call made at compile-time (in source code) would also have been illegal. This does appear to be a corner case though; the immediate window is perfectly capable of assigning generic variables and executing other code that would have been illegal at compile-time. Perhaps Roslyn will make things much more consistent.

If you wish, you can work around this like so:

genericDel.DynamicInvoke(42D);

(or)

((Action<double>)(object)genericDel)(42D);
孤君无依 2024-12-18 02:42:51

问题是您试图在知道“T”之前在创建委托的方法范围内调用委托。它试图将值类型(整数)转换为泛型类型“T”,这是编译器不允许的。如果你仔细想想,这是有道理的。只要您位于创建委托的方法的范围内,您就应该只能传入 T,否则它根本就不是通用的。

您需要等待方法返回,然后使用委托。完成后调用委托应该没有问题:

var a = CreateDelegate<double>(myFieldInfo[0], tst);     
var b = CreateDelegate(myFieldInfo[0], tst); 

a(434); 

The problem is that you are trying to invoke the delegate within the scope of the method that is creating it, before 'T' is known. It is trying to convert a value type (an integer) to the generic type 'T', which is not allowed by the compiler. If you think about it, it makes sense. You should only be able to pass in T as long as you are within the scope of the method that is creating the delegate, otherwise it wouldn't really be generic at all.

You need to wait for the method to return, then use the delegate. You should have no problem invoking the delegate after its completed:

var a = CreateDelegate<double>(myFieldInfo[0], tst);     
var b = CreateDelegate(myFieldInfo[0], tst); 

a(434); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文