public Jquery Extra(this HtmlHelper htmlhelper,
string message,
IDictionary<string, object> htmlAttributes)
如果我聲明這個Htmlhelper htmlhelper當我聲明我的方法,但我不想在我調用該方法時傳遞該參數?聲明參數,我不想通過
我是決策意識
public Jquery Extra(this HtmlHelper htmlhelper,
string message,
IDictionary<string, object> htmlAttributes)
如果我聲明這個Htmlhelper htmlhelper當我聲明我的方法,但我不想在我調用該方法時傳遞該參數?聲明參數,我不想通過
我是決策意識
我相信你正在試着編寫一個Extension Method。你定義它像這樣
namespace ExtensionMethods
{
public static class MyExtensions
{
public static Jquery Extra(this HtmlHelper htmlhelper, string message, IDictionary htmlAttributes)
{
//do work
return Jquery;
}
}
}
,然後用它是這樣的:
HtmlHelper helper = new HtmlHelper();
Jquery jq = helper.Extra(message, htmlAttributes);
我想你已經明白了。 – SLaks 2010-07-14 13:31:02
這不會工作HtmlHelper helper = new HtmlHelper(); 因爲HtmlHelper沒有構造函數。 – 2010-07-14 13:32:36
Brian的代碼僅僅是一個例子,用於證明您需要一個HtmlHelper變量來調用您的Extra擴展方法。重點在於語法必須是這樣的:'<你的HtmlHelper實例> .Extra(message,htmlAttributes);'你可能會在視圖中調用這個方法,在這種情況下,你已經可以訪問HtmlHelper實例(視圖的Html屬性),並且不需要創建它的新實例。你應該可以像'<%= Html.Extra(message,htmlAttributes)%>'或'<%JQuery jq = Html.Extra(message,htmlAttributes); %>' – 2010-07-14 14:28:24
編輯:這聽起來像你希望能夠在所有調用這個方法沒有任何HtmlHelper
對象。
如果方法需要HtmlHelper
,您將無法在沒有該方法的情況下調用它。
您應該重寫該方法,以便它不需要HtmlHelper
。
你可以用較少的參數過載:
public static Jquery Extra(this HtmlHelper htmlhelper, string message) {
return htmlHelper.Extra(message, null);
}
在C#4,你也可以使用一個可選的參數:
public Jquery Extra(this HtmlHelper htmlhelper, string message, IDictionary<string, object> htmlAttributes = null) {
我強烈建議您還增加了一個需要匿名類型的過載:
public static Jquery Extra(this HtmlHelper htmlhelper, string message, object htmlAttributes) {
return htmlHelper.Extra(message, null, new RouteValueDictionary(htmlAttributes));
}
但是我需要在我的方法中使用html助手,並且我不能創建它的新實例 – 2010-07-14 13:17:56
咦?你什麼意思? – SLaks 2010-07-14 13:18:44
我需要調用我的Extra方法而不傳遞第一個參數。但我不想通過htmlhelper而不是htmlattribuites。 所以,如果我創建一個超載我不會能夠使用htmlhelper變量,我想分配一個值。 – 2010-07-14 13:23:33
誰是這個函數的作者?如果是你,那麼不包含第一個參數。 public Jquery Extra(string message, IDictionary<string, object> htmlAttributes)
。
如果它是你自己沒有編寫的代碼,那麼HtmlHelper
變量可能是必要的,你應該不要試圖從函數原型中刪除它。
您的評論之一表示您無法初始化HtmlHelper,這在技術上並非如此。請參閱[msdn參考]。 1
這是我的代碼....我需要包括我需要在我的方法中使用它的HTML幫助.. 嗯,我的意思是你不能創建一個實例,他寫它的方式。 – 2010-07-14 14:43:25
您是否知道擴展方法和'this'-keyword?這很難理解你實際上想要做什麼 – sloth 2010-07-14 13:50:58