如何在C#.Net中创建原型方法(如JavaScript)?

时间:2020-03-05 18:38:18  来源:igfitidea点击:

如何在C#.Net中制作原型方法?

在JavaScript中,我可以执行以下操作为字符串对象创建trim方法:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

我该如何在C#.Net中进行此操作?

解决方案

回答

我们需要创建一个扩展方法,该方法需要.NET 3.5. 该方法需要在静态类中是静态的。该方法的第一个参数需要在签名中带有" this"前缀。

public static string MyMethod(this string input)
{
    // do things
}

然后,我们可以像这样称呼它

"asdfas".MyMethod();

回答

我们不能将方法动态地添加到.NET中的现有对象或者类中,除非更改该类的源。

但是,我们可以在C3.0中使用扩展方法,这些方法看起来像新方法,但却是编译时的魔术。

为此,请执行以下代码:

public static class StringExtensions
{
    public static String trim(this String s)
    {
        return s.Trim();
    }
}

要使用它:

String s = "  Test  ";
s = s.trim();

这看起来像一个新方法,但是将以与以下代码完全相同的方式进行编译:

String s = "  Test  ";
s = StringExtensions.trim(s);

我们到底想完成什么?也许有更好的方法来做我们想做的事?

回答

使用3.5编译器,我们可以使用扩展方法:

public static void Trim(this string s)
{
  // implementation
}

我们可以通过包含以下技巧,在针对CLR 2.0的项目(3.5编译器)上使用此功能:

namespace System.Runtime.CompilerServices
{
  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
  public sealed class ExtensionAttribute : Attribute
  {
  }
}

回答

听起来我们在谈论C#的扩展方法。通过在第一个参数之前插入" this"关键字,可以向现有类添加功能。该方法必须是静态类中的静态方法。 .NET中的字符串已经具有" Trim"方法,因此,我将使用另一个示例。

public static class MyStringEtensions
{
    public static bool ContainsMabster(this string s)
    {
        return s.Contains("Mabster");
    }
}

所以现在每个字符串都有一个非常有用的ContainsMabster方法,我可以这样使用它:

if ("Why hello there, Mabster!".ContainsMabster()) { /* ... */ }

请注意,我们还可以向接口(例如IList)添加扩展方法,这意味着实现该接口的任何类也将采用该新方法。

我们在扩展方法中声明的所有其他参数(在第一个" this"参数之后)都被视为普通参数。