0

我有一个下面定义的方法。

public static MvcHtmlString DisplayReadOnlyGrid(
    this HtmlHelper htmlHelper,
    string containerId, 
    MvcHtmlString innerHtml)
{
    try
    {
        var outerDiv = new TagBuilder("DIV");
        outerDiv.AddCssClass("ML5 MT5 MR5");
        outerDiv.MergeAttribute("id", containerId);
        if (innerHtml != null && !innerHtml.Equals(string.Empty))
        {
            outerDiv.InnerHtml = innerHtml.ToString();
        }
        return MvcHtmlString.Create(outerDiv.ToString());
    }
    catch 
    {                
        throw;
    }
}

当我调用这个方法时,我需要如下格式:

DisplayReadOnlyGrid(containerId="mycontainerid", innerHtml="innerhtml")

我怎样才能做到这一点?

4

4 回答 4

3

尝试这个:

html.DisplayReadOnlyGrid(containerId: "mycontainerid", innerHtml: "innerhtml");

您可以按任意顺序传递参数,并且可以同时传递位置参数和命名参数,但是出于显而易见的原因,命名参数必须跟在位置参数之后。

MSDN:http: //msdn.microsoft.com/en-us/library/dd264739.aspx

于 2012-10-12T12:13:58.773 回答
1

由于 C# 4.0 开箱即用,请参见此处。您无需执行任何操作即可启用它。
但是,请注意正确的语法使用冒号,而不是等号:

helper.DisplayReadOnlyGrid(containerId: "mycontainerid", innerHtml: "innerhtml");

如果您使用的是旧版本,则根本无法做到这一点。

于 2012-10-12T12:13:19.610 回答
0

Take a look at the MSDN here.

The format for using named arguments is as follows:

helper.DisplayReadOnlyGrid(containerId: "mycontainerid", innerHtml: "innerhtml");
于 2012-10-12T12:14:37.523 回答
0

Explanation for the method:

First its an extension method. Which is notable with the key word this in the parameters. To be precise its an extension method on HtmlHelper

Second the parameters: They are Named parameters(feature of C# 4.0) and you can call that method:

helper.DisplayReadOnlyGrid(containerId:"mycontainerid", innerHtml:"innerhtml")

Named parameters allow you to specify parameters in any order and are helpful with default parameters as well, which is also a new feature in C# 4.0

于 2012-10-12T12:15:03.947 回答