“非咖喱".NET 中的实例方法 [英] "Uncurrying" an instance method in .NET

查看:25
本文介绍了“非咖喱".NET 中的实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在创建时不指定实例的情况下创建实例方法的委托?换句话说,您能否创建一个静态"委托,该委托将调用方法的实例作为第一个参数?

Can you create a delegate of an instance method without specifying the instance at creation time? In other words, can you create a "static" delegate that takes as it's first parameter the instance the method should be called on?

例如,如何使用反射构造以下委托?

For example, how can I construct the following delegate using reflection?

Func<int, string> = i=>i.ToString();

我知道我可以使用methodInfo.Invoke,但速度较慢,并且在调用之前不会检查类型正确性.

I'm aware of the fact that I can use methodInfo.Invoke, but this is slower, and does not check for type-correctness until it is called.

当您拥有特定静态方法的MethodInfo时,可以使用Delegate.CreateDelegate(delegateType, methodInfo),并且静态方法的所有参数保持空闲.

When you have the MethodInfo of a particular static method, it is possible to construct a delegate using Delegate.CreateDelegate(delegateType, methodInfo), and all parameters of the static method remain free.

正如 Jon Skeet 指出的,如果方法在引用类型上是非虚拟的,您可以简单地应用相同的方法来创建实例方法的开放委托.决定在虚方法上调用哪个方法很棘手,所以这不是那么简单,而且值类型看起来根本不起作用.

As Jon Skeet pointed out, you can simply apply the same to make an open delegate of an instance method if the method is non-virtual on a reference type. Deciding which method to call on a virtual method is tricky, so that's no so trivial, and value-types look like they don't work at all.

对于值类型,CreateDelegate 表现出非常奇怪的行为:

For value types, CreateDelegate exhibits really weird behavior:

var func37 = (Func<CultureInfo,string>)(37.ToString);
var toStringMethod = typeof(int).GetMethod("ToString", BindingFlags.Instance | BindingFlags.Public, null, new Type[] {typeof(CultureInfo) }, null);
var func42 = (Func<CultureInfo,string>)Delegate.CreateDelegate(typeof(Func<CultureInfo,string>), 42, toStringMethod,true);
Console.WriteLine( object.ReferenceEquals(func37.Method,func42.Method)); //true
Console.WriteLine(func37.Target);//37
Console.WriteLine(func42.Target);//42
Console.WriteLine(func37(CultureInfo.InvariantCulture));//37
Console.WriteLine(func42(CultureInfo.InvariantCulture));//-201040128... WTF?

如果实例方法属于值类型(这适用于引用类型),则使用 null 作为目标对象调用 CreateDelegate 会引发绑定异常.

Calling CreateDelegate with null as the target object throws a binding exception if the instance method belonged to a value type (this works for reference types).

几年后的一些后续行动: 错误绑定的目标导致 func42(CultureInfo.InvariantCulture); 返回 "-201040128" 在我的示例中,不是 "42" 是内存损坏,这可能允许远程代码执行 (cve-2010-1898);这已于 2010 年在 ms10-060 安全更新.当前框架正确打印 42!这并没有让回答这个问题变得更容易,但解释了示例中特别奇怪的行为.

Some follow-up years later: The incorrectly-bound target that caused func42(CultureInfo.InvariantCulture); to return "-201040128" instead of "42" in my example was memory corruption that could have allowed remote code execution (cve-2010-1898); this was fixed in 2010 in the ms10-060 security update. Current frameworks correctly print 42! That doesn't make answering this question any easier, but explains the particularly weird behavior in the example.

推荐答案

您实际上选择了一个特别棘手的示例,原因有两个:

You've actually chosen a particularly tricky example, for two reasons:

  • ToString() 是从 object 继承的虚方法,但在 Int32 中被覆盖.
  • int 是值类型,当涉及到值类型和实例方法时,Delegate.CreateDelegate() 有一些奇怪的规则——基本上第一个有效参数变成ref int 而不是 int
  • ToString() is a virtual method inherited from object but overridden in Int32.
  • int is a value type, and there are weird rules with Delegate.CreateDelegate() when it comes to value types and instance methods - basically the first effective parameter becomes ref int rather than int

然而,这里有一个 String.ToUpper 的例子,它没有这些问题:

However, here's an example for String.ToUpper, which doesn't have either of those problems:

using System;
using System.Reflection;

class Test
{
    static void Main()
    {
        MethodInfo method = typeof(string).GetMethod
            ("ToUpper", BindingFlags.Instance | BindingFlags.Public,
             null, new Type[]{}, null);

        Func<string, string> func = (Func<string, string>)
            Delegate.CreateDelegate(typeof(Func<string, string>),
                                    null,
                                    method);

        string x = func("hello");

        Console.WriteLine(x);
    }
}

如果这对你来说足够好,那太好了...如果你真的想要 int.ToString,我将不得不更加努力:)

If that's good enough for you, great... if you really want int.ToString, I'll have to try a bit harder :)

下面是一个值类型的例子,它使用了一个新的委托类型,它通过引用来获取它的第一个参数:

Here's an example for a value type, using a new delegate type which takes its first parameter by reference:

using System;
using System.Reflection;

public struct Foo
{
    readonly string value;

    public Foo(string value)
    {
        this.value = value;
    }

    public string DemoMethod()
    {
        return value;
    }
}

class Test
{
    delegate TResult RefFunc<TArg, TResult>(ref TArg arg);

    static void Main()
    {
        MethodInfo method = typeof(Foo).GetMethod
            ("DemoMethod", BindingFlags.Instance | BindingFlags.Public,
             null, new Type[]{}, null);
        RefFunc<Foo, string> func = (RefFunc<Foo, string>)
            Delegate.CreateDelegate(typeof(RefFunc<Foo, string>),
                                    null,
                                    method);

        Foo y = new Foo("hello");
        string x = func(ref y);

        Console.WriteLine(x);
    }
}

这篇关于“非咖喱".NET 中的实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆