如何在 C#.Net 中制作原型方法?
在 JavaScript 中,我可以执行以下操作来为字符串对象创建一个 trim 方法:
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
{
}
}