问题描述
我有一个我想调用的带有私有方法的结构.由于我计划在性能关键部分执行此操作,因此我想缓存一个委托以执行该操作.问题是我似乎无法使用 Delegate.CreateDelegate 绑定到它的方法.有问题的结构不是我的创作,而是用于与第三方库的交互.有问题的结构如下所示::
I have a struct with a private method that I'd like to invoke. Since I plan to do this in a performance critical section, I'd like to cache a delegate to perform the action. The problem is I can't seem to bind to its method with Delegate.CreateDelegate. The struct in question is not my creation and is used in interaction with a third party library. The struct in question looks like this::
public struct A
{
private int SomeMethod()
{
//body go here
}
}
以下代码将失败并显示错误绑定到目标方法".
And the following code will fail with an "Error binding to target method".
Delegate.CreateDelegate(typeof(Func<A,int>),typeof(A).GetMethod("SomeMethod",BindingFlags.Instance | BindingFlags.NonPublic));
我知道我可以编写一个表达式树来执行该操作,但我不能使用我的正常 goto 来处理这些事情似乎很奇怪 Delegate.CreateDelegate
方法.
I know I can write an expression tree to perform the action, but it seems odd that I can't use my normal goto for these things the Delegate.CreateDelegate
method.
如果 A
是一个类,上面的代码就可以正常工作.之所以会出现这个问题,是因为 A
是一个结构.MSDN 文档对于 CreateDelegate 的这种重载是不正确的,因为它确实适用于非静态方法.
The above code works just fine if A
were a class. The issue only arises because A
is a struct.
MSDN documentation is incorrect for this overload of CreateDelegate as it does work on non-static methods.
推荐答案
有趣的问题.从这个错误报告来看,这可能是一个将在未来版本的 .NET 中修复的错误:http://connect.microsoft.com/VisualStudio/feedback/details/574959/cannot-create-open-instance-delegate-for-value-types-methods-which-implement-an-界面#details
Interesting problem. From this bug report, it looks like this might be a bug that will be fixed in a future version of .NET: http://connect.microsoft.com/VisualStudio/feedback/details/574959/cannot-create-open-instance-delegate-for-value-types-methods-which-implement-an-interface#details
实际上,我认为这个错误报告是关于一个不同的问题,所以你看到的行为实际上可能不是错误.
actually, I think this bug report is regarding a different issue, so the behavior you're seeing may not actually be a bug.
从该错误报告中,我了解到如果您将委托的第一个参数指定为通过引用传递,则可以解决此问题.下面是一个完整的工作示例:
From that bug report, I gleaned that there is a work-around if you specify the first argument of your delegate as being passed by reference. Below is a complete working example:
public struct A
{
private int _Value;
public int Value
{
get { return _Value; }
set { _Value = value; }
}
private int SomeMethod()
{
return _Value;
}
}
delegate int SomeMethodHandler(ref A instance);
class Program
{
static void Main(string[] args)
{
var method = typeof(A).GetMethod("SomeMethod", BindingFlags.Instance | BindingFlags.NonPublic);
SomeMethodHandler d = (SomeMethodHandler)Delegate.CreateDelegate(typeof(SomeMethodHandler), method);
A instance = new A();
instance.Value = 5;
Console.WriteLine(d(ref instance));
}
}
Jon Skeet's answer here 也讨论了这个问题.
这篇关于如何从结构的实例方法创建一个打开的委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!