gpt4 book ai didi

c# - 由于签名或安全透明性,Create Delegate 抛出绑定(bind)错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:40 28 4
gpt4 key购买 nike

我正在使用 C#4.0 和 .NET 4.5。

我有这个类,它是当前上下文中的入口点:

public static class HttpConfigurationImporter
{
public static readonly string ConfigurationMethodName = "Register";
public static readonly string ConfigClassName = "WebApiConfig";
public static readonly string HelpPageConfigClassName = "HelpPageConfig";

public static HttpConfiguration ImportConfiguration(string assemblyPath)
{
var assembly = Assembly.LoadFrom(assemblyPath);

string originalDirectory = Environment.CurrentDirectory;
Environment.CurrentDirectory = Path.GetDirectoryName(assemblyPath);

Type webApiConfigType = assembly
.GetTypes()
.FirstOrDefault(t => t.Name == ConfigClassName);

MethodInfo registerConfigMethod = webApiConfigType
.GetMethod(ConfigurationMethodName
, BindingFlags.Static | BindingFlags.Public);

//ERROR on this LINE
Action<HttpConfiguration> registerConfig = Delegate.
CreateDelegate(typeof(Action<HttpConfiguration>),
registerConfigMethod)
as Action<HttpConfiguration>;

HttpConfiguration config = new HttpConfiguration();
registerConfig(config);
ImportHelpPageConfiguration(assembly, config);
Environment.CurrentDirectory = originalDirectory;
return config;
}
}

当我尝试在另一个程序集中为以下目标创建委托(delegate)时......:

public static class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.MapHttpAttributeRoutes();
}
}

我收到错误:无法绑定(bind)到目标方法,因为它的签名或安全透明度与委托(delegate)类型不兼容。

如何解决?

最佳答案

删除这部分:

//ERROR on this LINE
Action<HttpConfiguration> registerConfig = Delegate.
CreateDelegate(typeof(Action<HttpConfiguration>),
registerConfigMethod)
as Action<HttpConfiguration>;

– 并尝试以这种方式调用 Register 方法

registerConfigMethod.Invoke(new object(), new object[] { config });

——代替

registerConfig(config);

它将像我的情况一样返回更准确的错误:

System.ArgumentException: 'Object of type 'System.Web.Http.HttpConfiguration' cannot be converted to type 'System.Web.Http.HttpConfiguration'.'

我有不同版本的 system.web.http.dll 用于构建程序集和执行此代码的程序集

关于c# - 由于签名或安全透明性,Create Delegate 抛出绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643571/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com