C#扩展方法重载导致“缺少程序集引用”错误
作者:互联网
我有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,extension-methods,c-5-0 来源: https://codeday.me/bug/20190612/1228578.html