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

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

问题描述

我需要创建一个委托类的非静态方法。并发症是,在创作的时候,我没有一个intance到类,只是它的类定义。在通话时我手头的实例。因此,我需要一种方法来:

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. 建立一个不完整delegat到成员方法,缺乏实例

  2. 通话1明确地传递类的intance委托。

都是那些可能吗?怎么样?
注:我愿意付出高昂的性能比较的价格为一个号码,但最好2不应该是一个很多比一个委托调用更昂贵

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.

推荐答案

您有两种选择,你可以把它像你这样的扩展方法。创建一个代表参加对象和任何可选参数,并通过这些参数来实际的函数调用。或者使用 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天全站免登陆