“不客气".NET 中的实例方法

quot;Uncurryingquot; an instance method in .NET(“不客气.NET 中的实例方法)
本文介绍了“不客气".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 中的实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)