C#扩展方法重载导致“缺少程序集引用”错误
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#扩展方法重载导致“缺少程序集引用”错误,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2818字,纯文字阅读大概需要5分钟。
内容图文
![C#扩展方法重载导致“缺少程序集引用”错误](/upload/InfoBanner/zyjiaocheng/803/309028a3e6974d539b5a51564af4514a.jpg)
我有2种扩展方法:
public static class ExtensionMethods
{
public static string GetClientIpAddress(this HttpRequestBase request)
{
// ...
}
public static string GetClientIpAddress(this HttpRequestMessage request)
{
// ...
}
}
类HttpRequestMessage位于System.Net.Http组件和HttpRequestBase是在System.Web程序(即,在不同的组件). ExtensionMethods类位于ProjectA中.
这个项目汇编得很好,没有任何问题.
然后我用第一种方法GetClientIpAddress(这HttpRequestBase要求)从另一个项目(可以说项目B),就像这样:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var sessionContext = DependencyResolver.Current.GetService<ISessionContext>();
// Call to GetClientIpAddress
sessionContext.ClientIpAddress =
filterContext.HttpContext.Request.GetClientIpAddress();
}
ProjectB已经引用了System.Web,但是当我尝试编译它时,它会导致编译器错误:
The type ‘
System.Net.Http.HttpRequestMessage
‘ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
‘.
我不明白的是为什么我要添加对System.Net.Http的引用.
看来,编译器试图使用第二种方法GetClientIpAddress(此HttpRequestMessage请求),这导致丢失参考组件.这是一个错误吗?
当我重命名第一种方法(即摆脱重载)时,一切都编译得很好.
解决方法:
从C#5.0规范,第7.5.3节:
Given the set of applicable candidate function members, the best function member in that set is located. If the set contains only one function member, then that function member is the best function member. Otherwise, the best function member is the one function member that is better than all other function members with respect to the given argument list, provided that each function member is compared to all other function members using the rules in §7.5.3.2.
第7.5.3.2节:
Given an argument list A with a set of argument expressions { E1, E2, …, EN } and two applicable function members MP and MQ with parameter types { P1, P2, …, PN } and { Q1, Q2, …, QN }, MP is defined to be a better function member than MQ if
? for each argument, the implicit conversion from EX to QX is not better than the implicit conversion from EX to PX, and
? for at least one argument, the conversion from EX to PX is better than the conversion from EX to QX.
没有规则“如果参数类型与参数类型完全匹配,则选择那个” – 因此编译器需要有关所有参数类型的完整类型信息,以便能够评估上述规则.
为了解决问题而无需添加对System.Net.Http的引用?您已经找到了答案 – 使用不同的方法名称.由于之前引用的7.5.3部分,这让你成功了:
If the set contains only one function member, then that function member is the best function member
内容总结
以上是互联网集市为您收集整理的C#扩展方法重载导致“缺少程序集引用”错误全部内容,希望文章能够帮你解决C#扩展方法重载导致“缺少程序集引用”错误所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。