Delegate.CreateDelegate无法绑定到struct member覆盖的错误是什么?

Mic*_*l B 5 c# delegates

在回答了这个问题后,我发现我必须使用一个ref参数来调用结构上的实例方法. 如何从struct的实例方法创建一个开放的Delegate?

我似乎无法绑定到显式接口实现之类的方法覆盖(以避免相关的拳击惩罚,(就IL而言,这实际上是覆盖的)),这是一个错误报告,说明在.NET的未来版本中,我们可以绑定到结构上的接口成员:https: //connect.microsoft.com/VisualStudio/feedback/details/574959/cannot-create-open-instance-delegate-for-value-types-methods-which-implement -an接口?WA = wsignin1.0#细节

但是,即使试图绑定到相同的部件Equals,GetHashCodeToString导致错误的发生如

public struct A
{
     public override int GetHashCode(){/*implementation goes here*/}
}
delegate TRet FuncByRef<TStruct,TRet>(ref TStruct) where TStruct:struct
Run Code Online (Sandbox Code Playgroud)

...

Delegate.CreateDelegate(typeof(FuncByRef<A,int>),typeof(A).GetMethod("GetHashCode"));
Run Code Online (Sandbox Code Playgroud)

将失败,并出现"绑定到目标方法时出错"的异常.

Mar*_*ell 0

让编译器担心如何,即

public static string SomeHelper(A obj) {
    return obj.SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)

然后绑定到“SomeHelper”。这也可能是所需的通用方法,它将使用神奇的“约束”操作码。

这也类似于

Func<A string> func = obj => obj.SomeMethod();
Run Code Online (Sandbox Code Playgroud)

如果您使用反射来获取方法,您可以尝试 DynamicMethod。