我有 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 中。
该项目编译良好,没有任何问题。
然后我使用另一个项目(比方说 ProjectB)的第一个方法 GetClientIpAddress(this HttpRequestBase request)
,如下所示:
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(this HttpRequestMessage request)
,这会导致缺少对程序集的引用。这是错误吗?
当我重命名第一个方法(即摆脱重载)时,一切都编译良好。
最佳答案
来自 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#扩展方法重载导致 "missing assembly reference"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17545933/