代码之家  ›  专栏  ›  技术社区  ›  GateKiller

如何在C.NET中创建原型方法(如javascript)?

  •  15
  • GateKiller  · 技术社区  · 16 年前

    如何在C.NET中生成原型方法?

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

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

    我该如何在C.NET中执行此操作?

    4 回复  |  直到 10 年前
        1
  •  20
  •   Lasse V. Karlsen    16 年前

    不能动态地向.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);
    

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

        2
  •  4
  •   Matt Hamilton    16 年前

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

        3
  •  0
  •   David Wengier    16 年前

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

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

    你可以这样称呼它

    "asdfas".MyMethod();
    
        4
  •  0
  •   Andrew Peters    16 年前

    使用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
      {
      }
    }