C# C中的自定义字符串帮助器

C# C中的自定义字符串帮助器,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我创建了一个助手方法,它接受一个字符串并用HTML换行符替换所有的换行符。我目前在助手类中有一个需要静态调用的方法 如何简单地将助手方法添加到内置的C字符串类中 这就是我希望能够做到的: m.MailingAddress = m.MailingAddress.ReplaceNewlines("<br />"); 这就是我目前正在做的: m.MailingAddress = Utility.ObjectExtensions.ReplaceNewlines(m.MailingAddre

我创建了一个助手方法,它接受一个字符串并用HTML换行符替换所有的换行符。我目前在助手类中有一个需要静态调用的方法

如何简单地将助手方法添加到内置的C字符串类中

这就是我希望能够做到的:

m.MailingAddress = m.MailingAddress.ReplaceNewlines("<br />");
这就是我目前正在做的:

m.MailingAddress = Utility.ObjectExtensions.ReplaceNewlines(m.MailingAddress,"<br />");

使用扩展方法创建静态类,如下所示:

public static class StringExtensions
{
    public static string ReplaceNewlines(this string text, string toReplace)
    {
       ...
    }
}

this关键字将方法标识为string类的扩展。

使用扩展方法创建静态类,如下所示:

public static class StringExtensions
{
    public static string ReplaceNewlines(this string text, string toReplace)
    {
       ...
    }
}

this关键字将该方法标识为string类的扩展。

像这样创建扩展方法为方便起见,将助手放在方法体中:

public static class StringHelpers
{
   public static ReplaceNewLinesExt(this string str, string replacement)
   {
      return Utility.ObjectExtensions.ReplaceNewlines(str, replacement);
   }
}
然后,在添加助手所在的命名空间后,可以使用如下扩展方法:

...
var modified = someString.ReplaceNewLinesExt("<br />");
...

您可以在

创建扩展方法中阅读有关扩展方法的更多信息,如下所示:为了方便起见,将助手放在方法体中:

public static class StringHelpers
{
   public static ReplaceNewLinesExt(this string str, string replacement)
   {
      return Utility.ObjectExtensions.ReplaceNewlines(str, replacement);
   }
}
然后,在添加助手所在的命名空间后,可以使用如下扩展方法:

...
var modified = someString.ReplaceNewLinesExt("<br />");
...

您可以在

中阅读有关扩展方法的更多信息。您可以使用扩展方法: 扩展方法应在静态类中声明

   public static class Helper
    {
       public static ReplaceNewLines(this string currentStr, string replaceWith)
       {
          return Utility.ObjectExtensions.ReplaceNewlines(currentStr, replaceWith);
       }
    }

单击查看更多详细信息。

您可以使用扩展方法: 扩展方法应在静态类中声明

   public static class Helper
    {
       public static ReplaceNewLines(this string currentStr, string replaceWith)
       {
          return Utility.ObjectExtensions.ReplaceNewlines(currentStr, replaceWith);
       }
    }

单击查看更多详细信息。

为什么不在元素空白处使用css:pre-line;相反,为什么不在元素空白处使用css:pre-line;相反,扩展方法基于扩展对象模式。必须注意的是,扩展方法只能用于。运算符ie.yourValue.yourExtensionMethodParameter可选,如果扩展方法位于不同的程序集中,则必须包含命名空间。扩展方法基于扩展对象模式。必须注意的是,扩展方法只能用于。运算符ie.yourValue.yourExtensionMethodParameter可选,如果扩展方法位于不同的程序集中,则必须包含命名空间。