Build a static delegate from non-static method(从非静态方法构建静态委托)
问题描述
我需要为类的非静态方法创建一个委托.复杂之处在于,在创建时我没有类的实例,只有它的类定义.在通话时,我确实有手头的实例.因此我需要一种方法:
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 调用委托,显式传递类的实例.
这两种可能吗?如何?注意:我愿意为第一个付出高昂的性能价格,但理想情况下,第二个不应比委托调用贵很多.
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
这篇关于从非静态方法构建静态委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从非静态方法构建静态委托


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01