且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TagBuilder AddCssClass顺序,添加到开头,如何在结尾添加新类?

更新时间:2022-04-22 19:10:44

查看代码此处,似乎无法使用您所使用的方法将类添加到最后。 AddCssClass的代码如下所示:

Looking at the code here, it doesn't seem like it's possible to add the class onto the end using the method that you are. The code for AddCssClass looks like this:

public void AddCssClass(string value)
{
    string currentValue;

    if (Attributes.TryGetValue("class", out currentValue))
    {
        Attributes["class"] = value + " " + currentValue;
    }
    else
    {
        Attributes["class"] = value;
    }
}

对于我们来说,TagBuilder对象公开了属性,因此我们可以编写一个扩展方法,将值添加到末尾而不是开头:

Fortunately for us, the TagBuilder object exposes Attributes, so we can write an extension method which adds the value to the end rather than the beginning:

public static class TagBuilderExtensions
{
    public void AddCssClassEnd(this TagBuilder tagBuilder, string value)
    {
        string currentValue;

        if (tagBuilder.Attributes.TryGetValue("class", out currentValue))
        {
            tagBuilder.Attributes["class"] = currentValue + " " + value;
        }
        else
        {
            tagBuilder.Attributes["class"] = value;
        }
    }
}

如果您有使用作为定义上述扩展方法的命名空间,您可以像这样简单地使用它:

And provided you have a using for the namespace you define the above extension method in, you can simply use it like so:

toolset.AddCssClassEnd("Number1");