[英]How can I create Prototype Methods (like JavaScript) in C#.Net?
如何在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
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.