我正在使用 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
用于构建程序集和执行此代码的程序集
我是一名优秀的程序员,十分优秀!