我写了几十种扩展方法,它们都按预期工作。但这是我第一次碰到这种情况下使用扩展方法。为什么我必须使用“this”从扩展类中调用扩展方法?
public static class ControllerExtensions
{
public static RedirectToRouteResult RedirectToAction<TController>(
this Controller controller
, Expression<Action<TController>> action
) where TController : Controller
{
RouteValueDictionary routeValuesFromExpression =
ExpressionHelper.GetRouteValuesFromExpression<TController>(action);
return new RedirectToRouteResult(routeValuesFromExpression);
}
}
看起来很正常吧?但在我的控制器中,我无法通过输入来访问此扩展方法。相反,我必须在关键字“this”前加上前缀。例如:
// This does not work, I get a compiler error because
// RedirectToAction has no overload for the generic.
//
return
RedirectToAction<MembershipController>(
c => c.RegisterSuccess(Server.UrlEncode(code)));
// But, this does work?!?!
//
return
this.RedirectToAction<MembershipController>(
c => c.RegisterSuccess(Server.UrlEncode(code)));
很奇怪。也许这是因为我在我正在扩展的实例对象内? “控制器”实例是?
果然,我能复制它在简单的控制台应用程序:“这个”
class Program
{
static void Main(string[] args)
{
var x = new TestClass();
x.Go<String>();
}
}
public class TestClass
{
public void Go()
{
}
public void NextMethod()
{
// compiler error. :(
Go<String>();
// works!
this.Go<String>();
}
}
public static class TestExtension
{
public static string Go<T>(this TestClass theClass)
{
return String.Empty;
}
}
那么,为什么工作?
这与ASP.NET或MVC控制器无关。我改变了问题标题和标签。 – M4N