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

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

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

我怎样才能在 C#.Net 中做到这一点?

有帮助吗?

解决方案

您无法向 .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);

您到底想实现什么目标?也许有更好的方法来做你想做的事?

其他提示

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

您需要创建一个扩展方法,这需要 .NET 3.5。该方法必须是静态的,位于静态类中。方法的第一个参数需要在签名中添加“this”前缀。

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

然后你可以这样称呼它

"asdfas".MyMethod();

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

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

您可以通过包含以下 hack 在 CLR 2.0 目标项目(3.5 编译器)上使用它:

namespace System.Runtime.CompilerServices
{
  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
  public sealed class ExtensionAttribute : Attribute
  {
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top