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

时间:2008-08-07 12:00:51

标签: c# .net

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

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

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

我怎样才能在C#.Net中执行此操作?

4 个答案:

答案 0 :(得分:20)

除非通过更改该类的源代码,否则无法动态地将方法添加到.NET中的现有对象或类中。

但是,您可以在C#3.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);

你到底想要完成什么?也许有更好的方法可以做你想做的事情?

答案 1 :(得分:4)

听起来你在谈论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”参数之后)被视为普通参数。

答案 2 :(得分:0)

您需要创建一个需要.NET 3.5的扩展方法。该方法需要在静态类中是静态的。该方法的第一个参数需要在签名中以“this”为前缀。

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

然后您可以将其称为

"asdfas".MyMethod();

答案 3 :(得分:0)

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

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

您可以在CLR 2.0目标项目(3.5编译器)上使用此功能,包括此hack:

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