我寫了幾十種擴展方法,它們都按預期工作。但這是我第一次碰到這種情況下使用擴展方法。爲什麼我必須使用「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