从非静态方法构建静态委托 [英] Build a static delegate from non-static method

查看:22
本文介绍了从非静态方法构建静态委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为类的非静态方法创建一个委托.复杂之处在于,在创建时我没有类的实例,只有它的类定义.在通话时,我确实有手头的实例.因此我需要一种方法:

I need to create a delegate to a non-static method of a class. The complications is that at the time of creation I don't have an intance to the class, only its class definition. At call time I do have the instance at hand. Thus I need a way to:

  1. 为成员方法构建一个不完整"的委托,缺少实例.
  2. 从 1 调用委托,显式传递类的实例.

这两种可能吗?如何?注意:我愿意为第一个付出高昂的性能价格,但理想情况下,第二个不应比委托调用贵很多.

Are both of those possible? How? Note: I'm willing to pay a high perfomance price for number one, but ideally 2 should not be a lot more expensive than a delegate call.

推荐答案

你有两个选择,你可以像对待扩展方法一样对待它.创建一个委托以接收对象和任何可选参数,并将这些参数传递给实际的函数调用.或者像 Dan 提到的那样使用 Delegate.CreateInstance 创建一个.

You have two options, you can treat it like you would an extension method. Create an delegate to take in the object and any optional arguments and pass those arguments to the actual function call. Or create one using Delegate.CreateInstance as Dan mentioned.

例如,

string s = "foobar";

// "extension method" approach
Func<string, int, string> substring1 = (s, startIndex) => s.Substring(startIndex);
substring1(s, 1); // "oobar"

// using Delegate.CreateDelegate
var stype = typeof(string);
var mi = stype.GetMethod("Substring", new[] { typeof(int) });
var substring2 = (Func<string, int, string>)Delegate.CreateDelegate(typeof(Func<string, int, string>), mi);
substring2(s, 2); // "obar"

// it isn't even necessary to obtain the MethodInfo, the overload will determine
// the appropriate method from the delegate type and name (as done in example 2).
var substring3 = (Func<int, string>)Delegate.CreateDelegate(typeof(Func<int, string>), s, "Substring");
substring3(3); // "bar"

// for a static method
var compare = (Func<string, string, int>)Delegate.CreateDelegate(typeof(Func<string, string, int>), typeof(string), "Compare");
compare(s, "zoobar"); // -1

这篇关于从非静态方法构建静态委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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